美文网首页
给View加任意圆角

给View加任意圆角

作者: 里克尔梅西 | 来源:发表于2021-09-06 10:43 被阅读0次

我们经常用到的设置圆角的方法

self.layer.maskToBouns = YES;
self.layer.cornerRadius = 15.f;

但是这样,如果遇到控件的高度小于想要设置的圆角的一半,择圆角最多只能设置成控件高度的一半,这样就与UI不符了。

所以就想要一个方法,包括xib也可以使用,可以任意设置控件四个圆角。

import UIKit

@IBDesignable
//任意圆角View

class ZXKCornerView: UIView {
    /// 左上角圆角
     @IBInspectable var topLeftCornerRadious: CGFloat = 0 {
         didSet {
             refreshCorner()
         }
     }
     /// 右上角圆角
     @IBInspectable var topRightCornerRadious: CGFloat = 0 {
         didSet {
             refreshCorner()
         }
     }
     /// 左下角圆角
     @IBInspectable var bottomLeftCornerRadious: CGFloat = 0 {
         didSet {
             refreshCorner()
         }
     }
     /// 右下角圆角
     @IBInspectable var bottomRightCornerRadious: CGFloat = 0 {
         didSet {
             refreshCorner()
         }
     }
     
     private func refreshCorner() {
         let maskLayer = CAShapeLayer()
         maskLayer.frame = bounds
         self.layer.mask = maskLayer
         
         let borderPath = UIBezierPath()
         // 起点
         borderPath.move(to: .init(x: 0, y: topLeftCornerRadious))
         // 左上角
         borderPath.addQuadCurve(to: .init(x: topLeftCornerRadious, y: 0), controlPoint: .zero)
         // 直线,到右上角
         borderPath.addLine(to: .init(x: bounds.width-topRightCornerRadious, y: 0))
         // 右上角圆角
         borderPath.addQuadCurve(to: .init(x: bounds.width, y: topRightCornerRadious), controlPoint: .init(x: bounds.width, y: 0))
         // 直线,到右下角
         borderPath.addLine(to: .init(x: bounds.width, y: bounds.height-bottomRightCornerRadious))
         // 右下角圆角
         borderPath.addQuadCurve(to: .init(x: bounds.width-bottomRightCornerRadious, y: bounds.height), controlPoint: .init(x: bounds.width, y: bounds.height))
         // 直线,到左下角
         borderPath.addLine(to: .init(x: bottomLeftCornerRadious, y: bounds.height))
         // 左下角圆角
         borderPath.addQuadCurve(to: .init(x: 0, y: bounds.height-bottomLeftCornerRadious), controlPoint: .init(x: 0, y: bounds.height))
         // 回到起点
         borderPath.addLine(to: .init(x: 0, y: topLeftCornerRadious))
         
         maskLayer.path = borderPath.cgPath
     }
     
     override func layoutSubviews() {
         super.layoutSubviews()
         refreshCorner()
     }
}

具体使用:

    ZXKCornerView *headCornerView = [[ZXKCornerView alloc] initWithFrame:CGRectMake(0, UILength(30), self.mytable.width, UILength(16))];
    headCornerView.backgroundColor = [UIColor whiteColor];
    headCornerView.topLeftCornerRadious = 24;
    headCornerView.topRightCornerRadious = 24;
    [headView addSubview:headCornerView];

相关文章

网友评论

      本文标题:给View加任意圆角

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