美文网首页iOS实用知识点
iOS对SDWebImage下载的图片进行圆角化处理

iOS对SDWebImage下载的图片进行圆角化处理

作者: 青藤1992 | 来源:发表于2017-09-19 23:35 被阅读444次

    工作三年了,都没写过博客,没想到第一篇居然在简书上写的。
    最近工作不好找啊,写点博客聊以自慰吧。不吐槽了,开始上正题吧。
    我们经常会遇到头像圆角问题,当然如果一个界面里就一个圆角的imageView,感觉也没必要优化。
    简单粗暴代码如下:

    imageView.layer.cornerRadius = CGRectGetWidth(imageView.bounds)/2;
    imageView.layer.masksToBounds = YES;
    

    但是当在一个tableView的每一个Cell中的imageView都要设置圆角的话,麻烦就来了。就会导致离屏渲染,让CPU处理它不擅长而GPU擅长的切图工作,让GPU等着渲染。一帧下来,CPU还没处理完,GPU只能不渲染了,这就引起了掉帧。滑动卡顿是必须的。
    当然了,用GPU去切图就好了,所以最好的办法就是对image进行处理,切圆角。我用了一个image的category添加一个方法处理图片圆角

    @interface UIImage (WebRadius)
    - (UIImage*)imageByRoundCornerRadius;
    @end
    
    @implementation UIImage (WebRadius)
    - (UIImage*)imageByRoundCornerRadius{
        UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(context, 1, -1);
        CGContextTranslateCTM(context, 0, -self.size.height);
        CGFloat minSize = MIN(self.size.width, self.size.height);
        CGRect rect = CGRectMake((self.size.width-minSize)/2, (self.size.height-minSize)/2, minSize, minSize);
        UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:minSize/2];
        [path closePath];
        CGContextSaveGState(context);
        [path addClip];
        CGContextDrawImage(context, rect, self.CGImage);
        CGContextRestoreGState(context);
        UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    @end
    

    图片只需要调用这个方法就可以进行image圆角处理。处理是在GPU中进行。(灵感来源于YYKit)
    那么对于网络加载的图片该怎么处理?
    我们很多人会使用SDWebImage进行网络请求图片,难道每次获取图片都要进行图片圆角化处理,然后显示吗?如果tableview一直滑动,那不是一直在圆角化处理吗?于是我想在SDWebImage从网络下载中对图片圆角化处理一下,然后保存在memory和disk中,再次从缓存中获取图片就不用圆角化处理了。SDWebImage在从网络下载图片成功后一般都会走SDImageCache的

    storeImage:imageData:forKey:toDisk:completion:

    方法进行保存。于是我使用了SDImageCache的category替换了storeImage:imageData:forKey:toDisk:completion:方法
    代码如下:

    @interface SDImageCache (WebRadius)
    @property (nonatomic,retain)NSNumber * isCornerRadius;
    @end
    
    @implementation SDImageCache (WebRadius)
    + (void)load{
        Method originalMethod = class_getInstanceMethod(self, @selector(storeImage:imageData:forKey:toDisk:completion:));
        Method myMethod = class_getInstanceMethod(self, @selector(lh_storeImage:imageData:forKey:toDisk:completion:));
        method_exchangeImplementations(originalMethod, myMethod);
    }
    static const char cornerRadiusKey = '\0';
    - (void)setIsCornerRadius:(NSNumber *)isCornerRadius{
        [self willChangeValueForKey:@"isCornerRadius"];
        objc_setAssociatedObject(self, &cornerRadiusKey, isCornerRadius, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self didChangeValueForKey:@"isCornerRadius"];
    }
    - (NSNumber*)isCornerRadius{
        return objc_getAssociatedObject(self, &cornerRadiusKey);
    }
    - (void)lh_storeImage:(nullable UIImage *)image
                imageData:(nullable NSData *)imageData
                   forKey:(nullable NSString *)key
                   toDisk:(BOOL)toDisk
               completion:(nullable SDWebImageNoParamsBlock)completionBlock
     {
        if (!image || !key) {
            if (completionBlock) {
                completionBlock();
            }
        return;
        }
        if ([self.isCornerRadius boolValue]) {
            image = [image imageByRoundCornerRadius];
            NSString * imageType = [self typeForImageData:imageData];
            if ([imageType isEqualToString:@"image/jpeg"]) {
                imageData = UIImageJPEGRepresentation(image, 1.0);
            }
            else if ([imageType isEqualToString:@"image/png"]){
                imageData = UIImagePNGRepresentation(image);
            }
        }
        Ivar memCachevar = class_getInstanceVariable([self class], [@"memCache" UTF8String]);
        if (memCachevar == nil) {
            memCachevar = class_getInstanceVariable([self class], [[NSString  stringWithFormat:@"_%@",@"memCache"] UTF8String]);
        }
        NSCache * memCache = object_getIvar(self, memCachevar);
        Ivar ioQueuevar = class_getInstanceVariable([self class], [@"ioQueue" UTF8String]);
        if (ioQueuevar == nil) {
            ioQueuevar = class_getInstanceVariable([self class], [[NSString stringWithFormat:@"_%@",@"ioQueue"] UTF8String]);
        }
        dispatch_queue_t  ioQueue = object_getIvar(self, ioQueuevar);
        if (self.config.shouldCacheImagesInMemory) {
            NSUInteger cost = image.size.height * image.size.width * image.scale * image.scale;
            [memCache setObject:image forKey:key cost:cost];
    }
        if (toDisk) {
            dispatch_async(ioQueue, ^{
                @autoreleasepool {
                    NSData *data = imageData;
                    if (!data && image) {
                        SDImageFormat imageFormatFromData = [NSData sd_imageFormatForImageData:data];
                        data = [image sd_imageDataAsFormat:imageFormatFromData];
                    }
                    [self storeImageDataToDisk:data forKey:key];
                }
                if (completionBlock) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completionBlock();
                    });
                }
            });
        }
        else {
            if (completionBlock) {
                completionBlock();
            }
        }
    }
    - (NSString *)typeForImageData:(NSData *)data {
        uint8_t c;
        [data getBytes:&c length:1];
        switch (c) {
            case 0xFF:
                return @"image/jpeg";
            case 0x89:
                return @"image/png";
            case 0x47:
                return @"image/gif";
            case 0x49:
            case 0x4D:
                return @"image/tiff";
         }
        return nil;
    }
    

    其中isCornerRadius是是否圆角的判断。这样就可以在不修改SDWebImage源码的情况下进行图片圆角操作了。不过主程序就得这样写

    [SDImageCache sharedImageCache].isCornerRadius = [NSNumber numberWithBool:YES];
    UIImageView * imageView = [[UIImageView alloc] init];
    imageView.backgroundColor = [UIColor clearColor];
    NSString * urlString = @"http://www.cdhdky.com/images/ttt.jpg";
    UIImage * image = [[SDImageCache sharedImageCache] imageFromCacheForKey:urlString];
    if (image) {
          imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
          imageView.center = self.view.center;
          imageView.image = image;
    }
    else{
        __weak __typeof(self) weakSelf = self;
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:urlString] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
            imageView.center = weakSelf.view.center;
            imageView.image = [[SDImageCache sharedImageCache]imageFromCacheForKey:imageURL.absoluteString];
        }];
    }
    [self.view addSubview:imageView];
    

    本人有点懒,如果有什么不懂的请留言。这个category有点缺陷需要继续完善。从今天起,开始分享我的知识,虽然我很笨。
    完整demo在github中

    相关文章

      网友评论

        本文标题:iOS对SDWebImage下载的图片进行圆角化处理

        本文链接:https://www.haomeiwen.com/subject/lfxnsxtx.html