1、設(shè)置簡單,性能差別不明顯,簡單圓角場景下推薦使用。
// 設(shè)置 layer 的 cornerRadius
view.layer.masksToBounds = YES;
view.layer.cornerRadius = imgSize.width / 2;
蘋果在iOS9后優(yōu)化了 cornerRadius 的繪圖方式,此種方式不再需要離屏渲染。
2、在位圖尺寸很大,數(shù)量很多的情況下,但要注意內(nèi)存警告,最好配合緩存機(jī)制使用,避免因內(nèi)存溢出而崩潰。
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;
}