iOS 设置圆角的几种方式
2023-02-01 本文已影响0人
搬砖的crystal
1.通过设置 layer
的属性
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 230, 100, 50)];
view.backgroundColor = [UIColor whiteColor];
view.layer.cornerRadius = 25;
view.layer.masksToBounds = YES;
// view.clipsToBounds = YES;
[self.view addSubview:view];
2.使用贝塞尔曲线 UIBezierPath
和 Core Graphics
框架画出一个圆角
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100,100,100,100)];
imageView.image= [UIImage imageNamed:@"1"];
//开始对imageView进行画图
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO,1.0);
//使用贝塞尔曲线画出一个圆形图
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip];
[imageView drawRect:imageView.bounds];
imageView.image=UIGraphicsGetImageFromCurrentImageContext();
//结束画图
UIGraphicsEndImageContext();
[self.view addSubview:imageView];
3.使用 CAShapeLayer
和贝塞尔曲线 UIBezierPath
设置圆角
UIView *view2 = [[UIImageView alloc]initWithFrame:CGRectMake(100,300,100,50)];
view2.backgroundColor = [UIColor whiteColor];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view2.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:view2.bounds.size];
CAShapeLayer *maskLayer =[[CAShapeLayer alloc]init];
//设置大小
maskLayer.frame = view2.bounds;
//设置图形样子
maskLayer.path = maskPath.CGPath;
view2.layer.mask= maskLayer;
[self.view addSubview:view2];
4.使用Quartz绘制
- (void)drawRect:(CGRect)rect {
// Drawing code
CGFloat width = rect.size.width;
CGFloat height = rect.size.height;
// 简便起见,这里把圆角半径设置为长和宽平均值的1/10
CGFloat radius = height * 0.5;
// 获取CGContext,注意UIKit里用的是一个专门的函数
CGContextRef context = UIGraphicsGetCurrentContext();
// 移动到初始点
CGContextMoveToPoint(context, radius, 0);
// 绘制第1条线和第1个1/4圆弧
CGContextAddLineToPoint(context, width - radius, 0);
CGContextAddArc(context, width - radius, radius, radius, -0.5 * M_PI, 0.0, 0);
// 绘制第2条线和第2个1/4圆弧
CGContextAddLineToPoint(context, width, height - radius);
CGContextAddArc(context, width - radius, height - radius, radius, 0.0, 0.5 * M_PI, 0);
// 绘制第3条线和第3个1/4圆弧
CGContextAddLineToPoint(context, radius, height);
CGContextAddArc(context, radius, height - radius, radius, 0.5 * M_PI, M_PI, 0);
// 绘制第4条线和第4个1/4圆弧
CGContextAddLineToPoint(context, 0, radius);
CGContextAddArc(context, radius, radius, radius, M_PI, 1.5 * M_PI, 0);
// 闭合路径
CGContextClosePath(context);
// 填充半透明黑色
CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 0.5);
CGContextDrawPath(context, kCGPathFill);
}