iOS设置圆角的4种方法

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 全部
*/

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值