iOS 加载大图

713 阅读1分钟
  • 苹果给出一个方法
func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage
    {
        let sourceOpt = [kCGImageSourceShouldCache : false] as CFDictionary
        // 其他场景可以用createwithdata (data并未decode,所占内存没那么大),
        let source = CGImageSourceCreateWithURL(imageURL as CFURL, 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)
    }
  • 使用
guard let path = Bundle.main.path(forResource: kLargeImageFilename, ofType: nil) else {
            NSLog("没有找到图片")
            return
        }
        let url = URL(fileURLWithPath: path)
        let size = CGSize(width: width, height: height)
        let scale = UIScreen.main.scale
        self.progressView.image = self.downsample(imageAt: url, to: size, scale: scale)