首页 文章

将调整大小的图像从Core Data插入UICollectionView的最简单方法是什么?

提问于
浏览
0

当我将图像从本地数组设置到每个集合视图单元格时,滚动是滞后的 . 这是因为在显示单元格时正在使用完整缩放的UIImage .

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell

    let image = images[indexPath.row]
    cell.imageView.image = image

    return cell
}

为了尝试解决这个问题,我编写了一个方法,可以在运行时将图像大小调整为适当的大小 .

private func resizeImages(images: [UIImage], size: CGSize) -> [UIImage?] {//...}

但是在 viewDidLoad 中调整阵列中所有图像的大小花费了相当长的时间 .

这是一个简单的相册应用程序,所以我宁愿避免使用任何活动或加载指标 . Given access to image data fetched from Core Data, how can I set the images in a collection view such that it won't lag while scrolling?

2 回答

  • 0

    而不是在运行时调整图像大小,您应该在保存 CoreData 时执行此任务 . 您应该存储两个图像,而不是保存一个图像 . 一个具有满刻度(高分辨率)和其他缩略图(调整大小) . 仅在 CollectionViewCell 中加载缩略图以避免滚动滞后 .

  • 0

    我使用了一个LazyImageView(最初来自cocoanetics.com)进行网络连接,它可能在你的情况下没有很多变化的情况下工作:

    import UIKit
    
    class LazyImageView: UIImageView {
        var loading = false
        weak var rawImage: UIImage?
    
        deinit {
            image = nil
            loading = false
        }
    
        override func didMoveToSuperview() {
            if !loading && image == nil{
                loading = true
                DispatchQueue.global().async {
                    self.resizeImage()
                }
            }
        }
    
        func resizeImage() {
            let resizedImage: UIImage? = nil
            // do the resizing
            DispatchQueue.main.async {
                self.image = resizedImage
                self.loading = false
            }
        }
    }
    

    正如你要求的那样简单,我会认为它已经完成了 .

    如果你想花更多的时间,你可以/应该考虑缓存(即到文件系统的缓存文件夹) .

    根据应用程序的不同,您可能还有另一种不错的用户体验方式可以为用户提供一些提示(即在加载前将正确的(?)占位符颜色设置为图像的背景) .

    考虑到@Bilal的答案,保存正确的拇指版声音也很好 . 这实际上取决于您的应用,即用户是否可以选择在集合视图中调整整体图像大小(现在或作为未来功能) .

相关问题