美文网首页技术重塑
关于圆角的5种处理方式

关于圆角的5种处理方式

作者: flowerflower | 来源:发表于2016-08-10 10:32 被阅读394次

    说明: 改造之前的圆角处理方式,新增加了两种,由于之前直接使用默认的富文本编辑,没有设置成Markdown编辑器,之前写的不能切换Markdown格式,所以只能再次重新在此添加了。
    原效果 -> 改造后效果

    1>无需任何代码直接在xib中实现:
    只需要如下图中的几步即可实现效果:
    其中的第4步
    Key Path:layer.cornerRadius
    type:Number
    Value:20(宽的一半 例如:原图宽为40)


    2>代码实现:
    // _header.clipsToBounds = YES;(_header就是图片的名称)
    // _header.layer.cornerRadius = 20;

    3>使用CAShapeLayer和UIBezierPath设置圆角

    //设置图片的尺寸大小
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    //设置图片
    imageView.image = [UIImage imageNamed:@"Snip20160726_2"];
    CGSize radio = CGSizeMake(5, 5);//圆角尺寸
    UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight|UIRectCornerBottomLeft|UIRectCornerBottomRight;//设置圆角位置
    /**
    *  bezierPathWithRoundedRect:imgViewd的大小
       byRoundingCorners:设置圆角的位置(左上、左下、右上、右下)
       cornerRadii:设置圆角尺寸
    */
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:corner cornerRadii:radio];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    //设置大小
    maskLayer.frame = imageView.bounds;
    //设置图形样子
    maskLayer.path = maskPath.CGPath;
    imageView.layer.mask = maskLayer;
    [self.view addSubview:imageView];
    

    4>使用贝塞尔曲线UIBezierPath和Core Graphics框架画圆

    //设置图片的尺寸大小
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    //设置图片
    imageView.image = [UIImage imageNamed:@"Snip20160726_2.png"];
    //开始对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];
    

    5>封装
    直接导入头文件即可直接调用:github送上门

    Snip20160810_2.png

    总结
    上面的第1种和第2种方式都是通过对图层进行直接改动,假设项目图片多的话就会变得卡,所以建议最好不要使用此种方式,此种方式最消耗性能。而第3种、第4种、第5种的优势在于:此种做法不是对控件或者图片做手脚,而是将服务器返回的正方形,通过绘制做成了圆形的图片,再把圆形的图片设置到imageView上去,这样就直接显示图片了。

    相关文章

      网友评论

      本文标题:关于圆角的5种处理方式

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