美文网首页
用贝塞尔曲线和CAShapeLayer添加圆角,边框

用贝塞尔曲线和CAShapeLayer添加圆角,边框

作者: 你忘记的无名人 | 来源:发表于2018-04-25 10:07 被阅读0次

    1.一般圆角或者边框都是一个app的修饰方式,所以最好是创建UIView的类别,以便不时之需.

    2.设置圆角-- 只需要白塞尔曲线来画就好了,简单,高效,且性能要比view的layer切的要好

       UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:cornerRadius];

        CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];

        //设置大小

        maskLayer.frame=self.bounds;

        //设置图形样子

        maskLayer.path= maskPath.CGPath;

        self.layer.mask= maskLayer;

    这里你需要了解的是UIBezierPath的类方法们:

    //-- 不切圆角 ---

    + (instancetype)bezierPathWithRect:(CGRect)rect;

    //--- 椭圆 ---

    +(instancetype)bezierPathWithOvalInRect:(CGRect)rect;

    // --- 圆角  ---- 四个角 都画

    + (instancetype)bezierPathWithRoundedRect:(CGRect)rect cornerRadius:(CGFloat)cornerRadius;

    // --- 圆角,选择行的 ---某个角落画 -- UIRectCorner由这个枚举决定,多个角用|连接--

    +(instancetype)bezierPathWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii;

    还有其他的方法,请自行查看,点进去,试试OK;

    3.设置边框,这就需要CAShapeLayer啦:

     // 获取贝塞尔曲线的路径

      UIBezierPath *maskPath = [UIBezierPath bezierPathWithRect:self.bounds];

    //这是边框

        CAShapeLayer *borderLayer=[CAShapeLayer layer];

    //设置边框的路径

        borderLayer.path= maskPath.CGPath;

    //边框的宽度

        borderLayer.lineWidth=2;

        borderLayer.fillColor  = [UIColor clearColor].CGColor;

    //边框的颜色

        borderLayer.strokeColor= bolderColor.CGColor;

    //这个需要注意的

        borderLayer.frame=self.bounds;

       [self.layeraddSublayer:borderLayer];

      注意:  borderLayer.frame=self.bounds,这句话就是边框的x值和视图的x值对齐,相当于把视图的边界为中心,向左向右(向上向下)加宽了2个像素(我的例子中),不是在里面或者在外面加粗,是在中间加粗.

    3.设置圆角+边框,记录下吧

      UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:cornerRadius];

        CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];

        //设置大小

        maskLayer.frame=self.bounds;

        //设置图形样子

        maskLayer.path= maskPath.CGPath;

        self.layer.mask= maskLayer;

        //如果有边框

            CAShapeLayer *borderLayer=[CAShapeLayer layer];

            borderLayer.path= maskPath.CGPath;

            borderLayer.fillColor  = [UIColor clearColor].CGColor;

             borderLayer.strokeColor= bolderColor.CGColor;

            borderLayer.lineWidth= bolderWidth;

            borderLayer.frame=self.bounds;

            [self.layeraddSublayer:borderLayer];

    需要说的是,这个方法是可以画出两个角或者一个角的,就是在获取贝塞尔曲线路径的时候用

    +(instancetype)bezierPathWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii;

    和UIRectCorner这个枚举组合;

    相关文章

      网友评论

          本文标题:用贝塞尔曲线和CAShapeLayer添加圆角,边框

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