1、设置简单,性能差别不明显,简单圆角场景下推荐使用。
// 设置 layer 的 cornerRadius
view.layer.masksToBounds = YES;
view.layer.cornerRadius = imgSize.width / 2;
苹果在iOS9后优化了 cornerRadius 的绘图方式,此种方式不再需要离屏渲染。
2、在位图尺寸很大,数量很多的情况下,但要注意内存警告,最好配合缓存机制使用,避免因内存溢出而崩溃。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = view.image;
image = [image drawCircleImage];
dispatch_async(dispatch_get_main_queue(), ^{
view.image = image;
});
});
////////////////////////
@implementation UIImage (RoundedCorner)
- (UIImage *)drawCircleImage {
CGFloat side = MIN(self.size.width, self.size.height);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(side, side), false, [UIScreen mainScreen].scale);
CGContextAddPath(UIGraphicsGetCurrentContext(),
[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, side, side)].CGPath);
CGContextClip(UIGraphicsGetCurrentContext());
CGFloat marginX = -(self.size.width - side) / 2.f;
CGFloat marginY = -(self.size.height - side) / 2.f;
[self drawInRect:CGRectMake(marginX, marginY, self.size.width, self.size.height)];
CGContextDrawPath(UIGraphicsGetCurrentContext(), kCGPathFillStroke);
UIImage *output = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return output;
}