ios – 为什么这段代码比天真的方法更好地解压缩UIImage?

前端之家收集整理的这篇文章主要介绍了ios – 为什么这段代码比天真的方法更好地解压缩UIImage?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的应用程序中,我需要加载大型JPEG图像并在滚动视图中显示它们.为了保持UI响应,我决定在后台加载图像,然后在主线程上显示它们.为了在后台完全加载它们,我强制每个图像被解压缩.我正在使用此代码压缩图像(请注意,我的应用程序仅限iOS 7,因此我了解在后台线程上使用这些方法是可以的):
  1. + (UIImage *)decompressedImageFromImage:(UIImage *)image {
  2. UIGraphicsBeginImageContextWithOptions(image.size,YES,0);
  3. [image drawAtPoint:CGPointZero];
  4. UIImage *decompressedImage = UIGraphicsGetImageFromCurrentImageContext();
  5. UIGraphicsEndImageContext();
  6. return decompressedImage;
  7. }

但是,我仍然有很长的加载时间,UI口吃和很多内存压力.我刚发现another solution

  1. + (UIImage *)decodedImageWithImage:(UIImage *)image {
  2. CGImageRef imageRef = image.CGImage;
  3. // System only supports RGB,set explicitly and prevent context error
  4. // if the downloaded image is not the supported format
  5. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  6.  
  7. CGContextRef context = CGBitmapContextCreate(NULL,CGImageGetWidth(imageRef),CGImageGetHeight(imageRef),8,// width * 4 will be enough because are in ARGB format,don't read from the image
  8. CGImageGetWidth(imageRef) * 4,colorSpace,// kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little
  9. // makes system don't need to do extra conversion when displayed.
  10. kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
  11. CGColorSpaceRelease(colorSpace);
  12.  
  13. if ( ! context) {
  14. return nil;
  15. }
  16. CGRect rect = (CGRect){CGPointZero,CGImageGetHeight(imageRef)};
  17. CGContextDrawImage(context,rect,imageRef);
  18. CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
  19. CGContextRelease(context);
  20. UIImage *decompressedImage = [[UIImage alloc] initWithCGImage:decompressedImageRef];
  21. CGImageRelease(decompressedImageRef);
  22. return decompressedImage;
  23. }

代码数量级更好.图像几乎立即加载,没有UI断断续续,内存使用率已经下降.

所以我的问题是双重的:

>为什么第二种方法比第一种方法好得多?
>如果第二种方法由于设备的独特参数而更好,是否有办法确保它对所有iOS设备(现在和未来)同样有效?我不想假设我的原生位图格式发生了变化,重新引入了这个问题.

解决方法

我假设你在Retina设备上运行它.在UIGraphicsBeginImageContextWithOptions中,您询问了默认比例,即主屏幕的比例,即2.这意味着它生成的位图大小为4倍.在第二个函数中,您以1x比例绘制.

尝试将1的比例传递给UIGraphicsBeginImageContextWithOptions,看看你的表现是否相似.

猜你在找的iOS相关文章