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

方法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。

转载于:https://juejin.im/post/5ac9ef74f265da239b41b67f

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值