iOS SDWebImage加载分辨率大图时,内存爆涨处理

我觉得sdwebimage的目的是给我们加载图片而已,像这种分辨率大不大的问题,人家哪里管的了那么多。最近项目中碰到一个坑,首页的图片大小居然有3300*3200,这么大的图显示完后,内存直接爆涨30M,当前就猜到问题所在。因为考虑到尽量不用动sdwebimage里面的深层代码,所以决定在最终显示的地方处理。

![image.png](https://upload-images.jianshu.io/upload_images/6476736-ada8f2262940c0f5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

反正是因为最终显示的地方才导致内存爆涨,只有将图片进行裁剪就好了,

@interface UIView (WebCache),最终找到了这个类,最好是button和imageview一起处理一下
- (void)sd_setImage:(UIImage *)image imageData:(NSData *)imageData basedOnClassOrViaCustomSetImageBlock:(SDSetImageBlock)setImageBlock transition:(SDWebImageTransition *)transition cacheType:(SDImageCacheType)cacheType imageURL:(NSURL *)imageURL {
    UIView *view = self;
    SDSetImageBlock finalSetImageBlock;
    if (setImageBlock) {
        finalSetImageBlock = setImageBlock;
    }
#if SD_UIKIT || SD_MAC
    else if ([view isKindOfClass:[UIImageView class]]) {
        UIImageView *imageView = (UIImageView *)view;
        finalSetImageBlock = ^(UIImage *setImage, NSData *setImageData) {
            //判断一下,如果图片分辨率很大,则进行裁剪
           UIImage *resultImage = [self compressResolvingImage:setImage];
           imageView.image = resultImage;
        };
    }
#endif
#if SD_UIKIT
    else if ([view isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)view;
        finalSetImageBlock = ^(UIImage *setImage, NSData *setImageData){
            [button setImage:setImage forState:UIControlStateNormal];
        };
    }
#endif

再下面代码进行裁剪

/**处理分辨率大的问题*/
- (UIImage*)compressResolvingImage:(UIImage*)orginImage
{
    if(orginImage == nil)return nil;
    if(orginImage.size.width > SCREEN_WIDTH || orginImage.size.height >SCREEN_HEIGHT){
        CGSize orginSize = orginImage.size;
        if(orginSize.width >SCREEN_WIDTH){
            orginSize.height = 1.0*SCREEN_WIDTH*orginSize.height/orginSize.width;
            orginSize.width = SCREEN_WIDTH;
        }else if (orginSize.height >SCREEN_HEIGHT){
            orginSize.width = 1.0*SCREEN_HEIGHT*orginSize.width/orginSize.height;
            orginSize.height = SCREEN_HEIGHT;
        }
       return [VAImageCompressTool ResizeImageWithImage:orginImage andSize:orginSize Scale:NO];
    }else{
        return orginImage;
    }
}

总结:其实不管是图片本身大,或者分辨率大,都可以在最终显示处进行处理,比起把人家源码改来改去的,这样还算简单方便。

你可能感兴趣的:(iOS SDWebImage加载分辨率大图时,内存爆涨处理)