首页 > 解决方案 > CollectionView [高分辨率] 图像上的 iOS 内存峰值

问题描述

我有一个具有 UIImageView 的单元格的 CollectionView。列表中的某些图像具有 3000 x 2000 以上的高分辨率。我正在使用 AlamofireImage 库来显示和缓存图像,但它仍然有巨大的峰值。我试着做

let filter = AspectScaledToFillSizeFilter(size: imageView.frame.size)
imageView.af_setImage(withURL: url, filter: filter)

这并没有太大的变化。

有没有更好的方法来调整下载图像的大小/降级分辨率,但在将其显示为 iOS 内存峰值之前,更多的是因为分辨率而不是图像文件的实际大小。

标签: iossdwebimagealamofireimagekingfisher

解决方案


斯威夫特 4.1

这就是我调整图像大小的方式。您可以在显示之前对其进行处理。

// Resize to ~1.5Kx2K resoultion and compress to <200KB (JPEG 0.2)
private func resizePhoto(_ originalPhoto: UIImage) -> UIImage? {
    var size: CGSize
    let scale = UIScreen.main.scale
    if originalPhoto.size.width > originalPhoto.size.height { // Landscape
        size = CGSize(width: 2016/scale, height: 1512/scale)
    } else { // Portrait
        size = CGSize(width: 1512/scale, height: 2016/scale)
    }
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    originalPhoto.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    let resizedPhoto = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    let scaledPhotoData = UIImageJPEGRepresentation(resizedPhoto!, 0.2)
    //print(">>> Resized data size: \(scaledPhotoData!.count)")
    return UIImage(data: scaledPhotoData)
}

推荐阅读