一款APP中对图片圆角的处理还是比较常见的,比如用户头像。iOS中处理图片圆角有3种方法,分别为:
- CALayer的cornerRadius和masksToBounds的配合;
- CALayer的mask;
- 利用CoreGraphics clip相应的圆角图像。
方法1和方法2性能低下,具体解释参见:
小心别让圆角成了你列表的帧数杀手
所以这儿主要讲解下方法3的实现,考虑到圆角处理是UIImageView中比较常见的处理,故而把圆角处理写在了分类中,以下是具体源码:
@implementation UIImageView (UIImageCorner)
- (void)cornerRadius:(CGFloat)radius
{
//创建一个图像上下文
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
//创建一个内切圆路径
[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) cornerRadius:radius] addClip];
//在指定区域内绘制图像
[self.image drawInRect:self.bounds];
//从当前图像上下文中取出之前回执的图像
self.image = UIGraphicsGetImageFromCurrentImageContext();
//删除之前创建的图像上下文
UIGraphicsEndImageContext();
}
@end