ios - Swift:如何提高从文档中加载图像的速度?
问题描述
我的应用程序将照片保存到本地文档文件夹,我使用 UICollectionView 显示该文件夹中的所有图像。但是每当我尝试打开 CollectionView 时,它通常需要几秒钟才能打开。我在想可能是图像文件太大,每张照片大约 10MB。我也尝试使用缩略图在 collectionview 中显示,但它仍然太慢。知道如何加快速度吗?
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SPCell
// Configure the cell
cell.imageView.image = loadImage(fileName: self.fileURLs[indexPath.row])
return cell
}
func loadImagesFromDocuments(){
let fileManager = FileManager.default
let documentsURL = NSHomeDirectory() + "/Documents/Secure/"
do {
fileURLs = try fileManager.contentsOfDirectory(at: URL(string: documentsURL)!, includingPropertiesForKeys: nil)
} catch {
print("Error while enumerating files : \(error.localizedDescription)")
}
}
func loadImage(fileName: URL) -> UIImage? {
do {
let imageData = try Data(contentsOf: fileName)
return UIImage(data: imageData)
} catch {
print("Error loading image : \(error)")
}
return nil
}
解决方案
当前的问题是每次出现单元格时都会加载图像,而不是
var fileURLs = [URL]()
做了
var fileImages = [UIImage]()
然后在里面viewDidLoad
fileImages = fileURLs.compactMap { self.loadImage(fileName: $0) }
推荐阅读
- amazon-web-services - AWS Api-Gateway 在收到来自外部服务的调用时是否支持 Mutual TLS?
- github - 如何获取我自己的 GitHub 事件有效负载 json 以在本地测试 GitHub 操作?
- django - 无法处理这种关联 - django app
- python-sql - 使用值列表替换 SQL 文件中的值
- javascript - 怎么写
悬停在 SVG 图像的特定部分
- javascript - 如何确定 HTML 形式的答案是否正确(通过 $.post 调用 PHP)而不透露答案?
- python - 追加到一个 numpy 数组而不将整个数组加载到 RAM 中
- python - Django Rest Framework djoser 激活问题
- javascript - AmCharts JS 承载认证
- laravel - 如何与我的身份验证建立两个角色的关系