1.实现方式
简易方式:
self.img1.layer.cornerRadius=self.img1.bounds.size.width/2;
self.img1.layer.masksToBounds=YES;
CoreGraphics剪裁方式
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
UIBezierPath *path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
[path addClip];
[image drawAtPoint:CGPointZero];
UIImage * newImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.img1.image = newImg;
2.性能测试
利用Instruments->Core Animation
测试环境是iphone7plus ios11.4
显示列表,多个圆角图片

A.使用简易模式
self.img1.layer.cornerRadius=self.img1.bounds.size.width/2;
self.img1.layer.masksToBounds=YES;
self.img2.layer.cornerRadius=self.img2.bounds.size.width/2;
self.img2.layer.masksToBounds=YES;
self.img3.layer.cornerRadius=self.img3.bounds.size.width/2;
self.img3.layer.masksToBounds=YES;
self.img4.layer.cornerRadius=self.img4.bounds.size.width/2;
self.img4.layer.masksToBounds=YES;
self.img5.layer.cornerRadius=self.img5.bounds.size.width/2;
self.img5.layer.masksToBounds=YES;
self.img1.image = image;
self.img2.image = image;
self.img3.image = image;
self.img4.image = image;
self.img5.image = image;
快速滑动列表的时候,基本不掉帧,GPU使用率15左右。

B.裁剪方式
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
UIBezierPath *path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
[path addClip];
[image drawAtPoint:CGPointZero];
UIImage * newImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.img1.image = newImg;
self.img2.image = newImg;
self.img3.image = newImg;
self.img4.image = newImg;
self.img5.image = newImg;
快速滑动列表的时候,卡顿明显,GPU使用率30左右。

是不是很诡异,和我们想的不太一样。
其实,如果使用CoreGraphics,最好异步绘制。
dispatch_async(dispatch_get_global_queue(0, 0), ^{
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
UIBezierPath *path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
[path addClip];
[image drawAtPoint:CGPointZero];
UIImage * newImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
self.img1.image = newImg;
self.img2.image = newImg;
self.img3.image = newImg;
self.img4.image = newImg;
self.img5.image = newImg;
});
});
快速滑动列表的时候,虽然基本不掉帧,但是GPU使用率20左右。

综上所述:在当前测试环境下,简易方式设置圆角完全没有性能问题(系统对于该方法进行了优化)。
网友评论