如何高效的给UIImageView加一个圆角(含cache缓存)

438 阅读1分钟

方法1

self.view.layer.cornerRadius = 5;
self.view.layer.masksToBounds = YES;

使用cornerRadius会导致offscreen drawing有性能问题,因此不推荐使用此方法

方法2

使用Core Graphics为UIImageView绘制圆角

-(UIImage *)bezierCircleImage:(CGRect) rect andCornerRadius:(CGFloat)cornerRadius {
    

    //开始对imageView进行画图
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    //使用贝塞尔曲线画出一个圆形图
    [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius] addClip];
    [self drawInRect:rect];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    
    //结束画图
    UIGraphicsEndImageContext();

    return image;
    
}

考虑到实际使用过程中的性能,我们不能每次用到圆角时都对图像进行绘制,因此还要对圆角图片进行cache缓存


#import "UICircleImageView.h"

@implementation UICircleImageView {
    NSCache *_cache;
}


- (id)init {
    if ((self = [super init])) {
        _cache = [NSCache new];
        //将cache的size设置为50m
        _cache.countLimit = 100;
        _cache.totalCostLimit = 50 * 1024 * 1024;
    }
    return self;
}

-(UIImage *)bezierCircleImage:(CGRect) rect andCornerRadius:(CGFloat)cornerRadius data:(NSData *)data{
    
    NSData *cacheData = [_cache objectForKey:data];
    if (cacheData) {
        //cache hit
        return [UIImage imageWithData:cacheData];
    } else {
        //cache miss
        //开始对imageView进行画图
        UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
        //使用贝塞尔曲线画出一个圆形图
        [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius] addClip];
        UIImage* dataImage = [[UIImage alloc] initWithData:data];
//        [dataImage drawinRect:rect];
        [dataImage drawInRect:rect];
        UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
        NSData* imageData = UIImagePNGRepresentation(image);
        //结束画图
        UIGraphicsEndImageContext();
        
        [_cache setObject:imageData forKey:data cost:imageData.length];
        
        return image;
        
    }
    
}

创建一个UIImageView的子类UICircleImageView,利用NSCache来实现缓存,利用UIImage的data作为key将每一张图片的圆角存入cache中,在每次要获取圆角图片之前,在cache中进行查找,如果找到则使用cache中的图片,如果没有找到则进行绘制并将绘制得到的圆角图片存入cache。