美文网首页
iOS  设置圆角的几种方式

iOS  设置圆角的几种方式

作者: 搬砖的crystal | 来源:发表于2023-02-01 10:57 被阅读0次
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.使用贝塞尔曲线 UIBezierPathCore 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);
}

相关文章

网友评论

      本文标题:iOS  设置圆角的几种方式

      本文链接:https://www.haomeiwen.com/subject/lzkihdtx.html