[关闭]
@binbins 2017-06-23T19:03:22.000000Z 字数 1176 阅读 181

解决加载大量图片时的崩溃问题

原文链接

bug SDWebImage


1.UIImage+MultiFormat这个类里面添加如下压缩方法

  1. +(UIImage *)compressImageWith:(UIImage *)image
  2. {
  3. float imageWidth = image.size.width;
  4. float imageHeight = image.size.height;
  5. float width = 640;
  6. float height = image.size.height/(image.size.width/width);
  7. float widthScale = imageWidth /width;
  8. float heightScale = imageHeight /height;
  9. // 创建一个bitmap的context
  10. // 并把它设置成为当前正在使用的context
  11. UIGraphicsBeginImageContext(CGSizeMake(width, height));
  12. if (widthScale > heightScale) {
  13. [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
  14. }
  15. else {
  16. [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
  17. }
  18. // 从当前context中创建一个改变大小后的图片
  19. UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  20. // 使当前的context出堆栈
  21. UIGraphicsEndImageContext();
  22. return newImage;
  23. }

2.修改sd_imageWithData方法:选择性的压缩image

  1. image = [[UIImage alloc] initWithData:data];
  2. if (data.length/1024 > 128) {
  3. image = [self compressImageWith:image];
  4. }

3.在SDWebImageDownloaderOperation中方法添加两行代码

  1. UIImage *image = [UIImage sd_imageWithData:self.imageData];
  2. //将等比压缩过的image在赋在转成data赋给self.imageData
  3. NSData *data = UIImageJPEGRepresentation(image, 1);
  4. self.imageData = [NSMutableData dataWithData:data];

4.在sd_setImageWithURL方法后调用

  1. [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注