ios - 滚动条上的主线程阻塞和 Kingfisher 设置图像

标签 ios swift kingfisher

我的滚动性能一直很慢,我注意到当我滚动并且使用非缓存图像调用 setImage 时,性能会在下载时滞后。

if let imageURL = URL(string: presentable.imageUrl) {
    let resource = ImageResource(downloadURL: imageURL)
    photoView.kf.setImage(with: resource, options: [.transition(.fade(0.2))])
}

我的理解是翠鸟在后台线程下载这些,然后在主线程上显示它们,但主线程似乎暂时被阻塞了。删除 .transition 对这种情况没有帮助。

关于如何提高我的滚动性能的任何想法?谢谢

最佳答案

当图像大于 ImageView 时,iOS 需要操作大型 UIImage 对象,这会导致 UI 出现明显的卡顿现象。您可以通过在使用图像之前调整图像大小来防止出现该问题。

幸运的是,Kingfisher 有一个处理器可以为您调整这些(在后台线程中)的大小。作为Cheat Sheet说:

Using DownsamplingImageProcessor for high resolution images

Think about the case we want to show some large images in a table view or a collection view. In the ideal world, we expect to get smaller thumbnails for them, to reduce downloading time and memory use. But in the real world, maybe your server doesn't prepare such a thumbnail version for you. The newly added DownsamplingImageProcessor rescues [sic]. It downsamples the high-resolution images to a certain size before loading to memory:

imageView.kf.setImage(
    with: resource,
    placeholder: placeholderImage,
    options: [
        .processor(DownsamplingImageProcessor(size: imageView.size)),
        .scaleFactor(UIScreen.main.scale),
        .cacheOriginalImage
    ])

Typically, DownsamplingImageProcessor is used with .scaleFactor and .cacheOriginalImage. It provides a reasonable image pixel scale for your UI, and prevent future downloading by caching the original high-resolution image.

我用小图片创建了一个小测试并确认它如丝般顺滑,但是当我使用大图片时,我在滚动行为中遇到了卡顿。但是当我在大图场景下加上这个DownsamplingImageProcessor后,又是丝般顺滑了。

关于ios - 滚动条上的主线程阻塞和 Kingfisher 设置图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54082478/

相关文章:

ios - 我收到内存警告并且我的应用程序崩溃了。它会杀死自动释放对象吗?

ios - 文件下载完成后检查内容类型 nsurlsessiondownloadtask

ios - 尝试将图像 URL 作为字符串获取时应用程序崩溃

ios - 翠鸟导致主线程问题

ios - 翠鸟图像采用全宽

iphone - 设置与 Facebook 的连接未按预期工作 (iPhone)

ios - 在同一项目中使用私有(private) Pod 和公共(public) Pod

ios - 如何从 iOS 在 WhatsApp 上分享内容

Swift:守卫 let 与 if let

objective-c - AREnvironmentProbeAnchor 不存在于 ARFrame anchor 中