iOS切圆角的方式有三种
1. 通过设置layer的属性
最简单的一种,但是很影响性能,一般在正常的开发中使用很少.
self.button.layer.cornerRadius = 30; self.button.layer.masksToBounds = YES;
2.使用贝塞尔曲线UIBezierPath和Core Graphics 使用不多 貌似只能使用ImageView 这个不太懂
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]; imageView.center = self.view.center; imageView.image = [UIImage imageNamed:@"1"]; //开始对imageView进行画图 UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale); //使用贝塞尔曲线画出一个圆形图 [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip]; [imageView drawRect:imageView.bounds]; imageView.image = UIGraphicsGetImageFromCurrentImageContext(); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); [self.button setImage:image forState:UIControlStateNormal]; //结束画图 UIGraphicsEndImageContext(); [self.view addSubview:imageView];
3.使用CAShapeLayer和UIBezierPath设置圆角
// 只切一个角 // UIBezierPath *maskPAth = [UIBezierPath bezierPathWithRoundedRect:self.button.bounds byRoundingCorners:UIRectCornerTopLeft cornerRadii:self.button.bounds.size]; // 只切两个角 // UIBezierPath *maskPAth = [UIBezierPath bezierPathWithRoundedRect:self.button.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)]; // 注意 当size是整个大小时 切角是对角线会切成圆 size不是整个视图大小不会成圆角 有人说必须导入<AVFoundation/AVFoundation.h> 我是没有发现 如果不行可以导入试试 // UIBezierPath *maskPAth = [UIBezierPath bezierPathWithRoundedRect:self.button.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:self.button.bounds.size]; // UIBezierPath *maskPAth = [UIBezierPath bezierPathWithRoundedRect:self.button.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)]; // 三个角 // UIBezierPath *maskPAth = [UIBezierPath bezierPathWithRoundedRect:self.button.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight | UIRectCornerTopRight cornerRadii:CGSizeMake(30, 30)]; // 四个角 // UIBezierPath *maskPAth = [UIBezierPath bezierPathWithRoundedRect:self.button.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:self.button.bounds.size]; // UIBezierPath *maskPAth = [UIBezierPath bezierPathWithRoundedRect:self.button.bounds cornerRadius:10]; // CAShapeLayer *caShapeLayer = [CAShapeLayer layer]; // caShapeLayer.path = maskPAth.CGPath; // self.button.layer.mask = caShapeLayer;
这三种方法中第三种最好,对内存的消耗最少啊,而且渲染快速。
注意:这三种方法都是显示的是圆角,并不是真实切除角,在debug view hierarchy上可以看出大小不变 显示改变