项目中需要加载大量本地图片,导致内存暴涨
将UIImage(named: "xxx")
修改成:
let wid = xxxx
let hei = xxxx
let filePath = Bundle.main.path(forResource: model.goods_id, ofType: "png")
if filePath != nil {
let data = NSData.init(contentsOfFile: filePath ?? "")
if data != nil {
let image = getImageFromData(imageAt: data!, to: CGSize(width: wid, height: hei), scale: 3)
goodsImageView.image = image
} else {
goodsImageView.image = nil
}
} else {
goodsImageView.image = nil
}
//pointSize 图片尺寸(点)
func getImageFromData(imageAt imageData: NSData, to pointSize: CGSize, scale: CGFloat) -> UIImage
{
let sourceOpt = [kCGImageSourceShouldCache : false] as CFDictionary
//(data并未decode,所占内存没那么大),
let source = CGImageSourceCreateWithData(imageData as CFData, sourceOpt)!
let maxDimension = max(pointSize.width, pointSize.height) * scale //像素大小
let downsampleOpt = [kCGImageSourceCreateThumbnailFromImageAlways : true,
kCGImageSourceShouldCacheImmediately : true,
kCGImageSourceCreateThumbnailWithTransform : true,
kCGImageSourceThumbnailMaxPixelSize : maxDimension] as CFDictionary
let downsampleImage = CGImageSourceCreateThumbnailAtIndex(source, 0, downsampleOpt)!
return UIImage(cgImage: downsampleImage)
}
内存占用下降明显。 imageNamed: 加载本地图片会保留在全局缓存中
在长列表中,加载大量本地图片,这种方式加载图片虽然可以明显的减少内存的占用,但会造成滑动卡顿,需要做预加载