iOS设置圆角的4种方法

2023-05-16

1 直接layer层的设置(不推荐)
其中的masksToBounds会实现离屏渲染 GPU会在当前屏幕缓冲区开辟一个新的缓冲区进行工作 也就是离屏渲染 这会给我们带来额外的性能损耗 如果这样的圆角操作达到一定数量 会触发缓冲区的频繁合并和上下文的频繁切换 性能上宏观提现是掉帧 不建议使用 iOS9以后系统会判断 能不产生离屏渲染的就不用了

UIImageView *imgTest = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
imgTest.image = [UIImage imageNamed:@"test.jpg"];
[self.view addSubview:imgTest];
imgTest.layer.cornerRadius = 50;
imgTest.layer.masksToBounds = YES;

2 贝塞尔曲线+CoreGraphics(推荐)

//创建新的位图
//size 新位图的大小 opaque 透明开关 scale 缩放因子 设置为0 系统自动匹配
UIGraphicsBeginImageContextWithOptions(imgTest.bounds.size, NO, 0);
//用贝塞尔曲线画一个圆形 addClip 进行切割
[[UIBezierPath bezierPathWithRoundedRect:imgTest.bounds cornerRadius:50] addClip];
//开始绘图
[imgTest drawRect:imgTest.bounds];
imgTest.image = UIGraphicsGetImageFromCurrentImageContext();
//结束画图
UIGraphicsEndImageContext();

3 CoreGraphics(推荐)

UIGraphicsBeginImageContextWithOptions(imgTest.bounds.size, NO, 0);
//获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//设置一个范围
CGRect rect = CGRectMake(0, 0, imgTest.bounds.size.width, imgTest.bounds.size.height);
//给上下文画一个椭圆
CGContextAddEllipseInRect(ctx, rect);
//裁剪
CGContextClip(ctx);
//开始绘图
[imgTest drawRect:imgTest.bounds];
imgTest.image = UIGraphicsGetImageFromCurrentImageContext();
//结束
UIGraphicsEndImageContext();

4 CAShapeLayer+贝塞尔曲线(不推荐)

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imgTest.bounds byRoundingCorners:UIRectCornerTopRight|UIRectCornerTopLeft cornerRadii:CGSizeMake(50, 50)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
//设置切割的范围和路径
maskLayer.frame = imgTest.bounds;
maskLayer.path = maskPath.CGPath;
mgTest.layer.mask = maskLayer;
//相比之下第四种更加简洁 但是有mask 会产生离屏渲染
//还可以规定范围UIRectCorner
/*UIRectCornerTopLeft 上左
UIRectCornerTopRight 上右
UIRectCornerBottomLeft 下左
UIRectCornerBottomRight 下右
UIRectCornerAllCorners 全部
*/

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS设置圆角的4种方法 的相关文章

随机推荐