我有一个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。上面的图片加载有什么问题或者需要进一步优化吗?
更新:时间分析器结果
最佳答案
您已经发现您正在主队列上再次加载 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/