ios - 异步加载的 UICollectionView 速度慢

标签 ios asynchronous swift uiimage uicollectionview

我有一个UICollectionView,它加载iPad内存的图像并将它们显示在网格中,就像Apple的照片应用程序一样。 UICollectionViewCell 异步加载缩略图:

 func setImage(img:String){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
            //load the image in the background
            let image = UIImage(contentsOfFile: img)
            //when done, assign it to the cell's UIImageView
            dispatch_async(dispatch_get_main_queue(), {
                if let imageView = self.imageView{
                    imageView.image = UIImage(contentsOfFile: img)
                }
            })
        })
    }

但是, ScrollView 时会出现滞后,就像在等待图像加载一样,尤其是使用 Retina 图形时。单元格和图像的大小约为 240x180px。上面的图片加载有什么问题或者需要进一步优化吗?

更新:时间分析器结果 enter image description here

最佳答案

您已经发现您正在主队列上再次加载 UIImage;解决这个问题会有帮助。

UIImage 在大多数情况下延迟加载其内部图像数据。一个技巧是在仍在后台队列上时调用其 CGImage 属性,以强制它实际创建其内部图像数据,而不是在第一次绘制 ImageView 时延迟加载它:

func setImage(img:String){
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        //load the image in the background
        let image = UIImage(contentsOfFile: img)
        image.CGImage // <- Force UIImage to not lazy load the data
        //when done, assign it to the cell's UIImageView
        dispatch_async(dispatch_get_main_queue(), {
            if let imageView = self.imageView {
                imageView.image = image
            }
        })
   })
}

注意:如果您有很多图像,那么这样做可能很快就会收到内存警告。如果这样做,这可能不会有帮助,因为内存警告通常会导致 UIImage 再次清除其内部图像数据以释放资源。

关于ios - 异步加载的 UICollectionView 速度慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26186688/

相关文章:

c# - 由于极不可能的情况发生而丢失数据包?

ios - 从数组中选择 UIlabel 背景颜色,然后将其从数组中删除。 ( swift )

swift - 永远不会使用不可变值 X 考虑用 Swift 2 中的 '_' 错误替换

ios - Array.contains 返回 false

python - celery 运行错误

c# - 如何正确地对异步套接字连接操作进行单元测试并避免 Thread.Sleep?

swift - 如何在 Vapor 3 中将字典转换为 JSON?

ios - 向 Storyboard添加额外的预览设备 Xcode 10+

ios - [iOS]如何省略协议(protocol)?

ios - 如何在 Swift 中制作一个可点击的 UITextView?