Swift缩减大图片像素采样以展示小尺寸图片
2022-11-30 本文已影响0人
Xtuphe
Downsampling large images for display at smaller size
有助于内存优化
class func downsample(imageAt imageURL:URL, to pointSize:CGSize, scale:CGFloat) -> UIImage {
let imageSourceOptions = [kCGImageSourceShouldCache:false] as CFDictionary
let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions)!
let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
let downsampleOptions = [
kCGImageSourceCreateThumbnailFromImageAlways:true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
] as CFDictionary
let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions)!
return UIImage(cgImage: downsampledImage)
}