iOS 生成自定义圆角的UIView

项目中经常需要用到圆角矩形需要单独一个角是直角,或者单独一个角是圆角的情况

而通常这种需求的场景又要求矩形UI不是固定大小的,比如聊天气泡

基于此使用UIBezierPath 绘制一个自由控制 各个角、背景颜色、边框颜色和大小的工具就非常有必要

1.首先生成Layer用来添加UIBezierPath

   shape= [[CAShapeLayeralloc]init];

    shape.frame = self.bounds;

2.设置边框和背景色

    shape.strokeColor = _lineColor;

    shape.fillColor=  _bgColor;

3.初始化UIBezierPath

    UIBezierPath *path = [UIBezierPath bezierPath];

    path.lineWidth=self.lineWidth;//线宽

    path.lineCapStyle = kCGLineCapRound;

    path.lineJoinStyle = kCGLineJoinRound;

      CGFloat width = rect.size.width;

    CGFloat height = rect.size.height;

4.绘制四边线,需要把圆角空间空出--- inset 为自定义结构,包含CGFloat left, right, right_down, left_down 用来设置圆角

//左

    [pathmoveToPoint:CGPointMake(inset.left,0)];

    [pathaddLineToPoint:CGPointMake(width-inset.right,0)];//上线

    //右

    [pathmoveToPoint:CGPointMake(width, inset.right)];

    [pathaddLineToPoint:CGPointMake(width, height-inset.right_down)];//右线

    //右下

    [pathmoveToPoint:CGPointMake(width-inset.right_down, height)];

    [pathaddLineToPoint:CGPointMake(inset.left_down, height)];//下线

    //左下

    [pathmoveToPoint:CGPointMake(0, height-inset.left_down)];

    [pathaddLineToPoint:CGPointMake(0, inset.left)];//左线

5.绘制带角度的圆角

//左

    [path addArcWithCenter:CGPointMake(inset.left, inset.left) radius:inset.left startAngle:-M_PI endAngle:-0.5 * M_PI clockwise:YES];

    //右

    [path addArcWithCenter:CGPointMake(width - inset.right, inset.right) radius:inset.right startAngle:-0.5 *M_PI endAngle:0 clockwise:YES];

    //右下

    [path addArcWithCenter:CGPointMake(width-inset.right_down, height-inset.right_down)radius:inset.right_downstartAngle:0endAngle:-1.5*M_PIclockwise:YES];

    //左下

    [path addArcWithCenter:CGPointMake(inset.left_down, height-inset.left_down) radius:inset.left_down startAngle:-1.5 * M_PI endAngle:-1 * M_PI clockwise:YES];

6.绘制

    shape.path= path.CGPath;

    shape.lineWidth = self.lineWidth;

    [self.layer insertSublayer:shape atIndex:0];

Note:

只把具体怎么做放上,也没心思解释为什么每一步这么写,愿意看的一看就懂;

代码里没有的参数自行定义即可

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容