xib 高效 tip | 给你的 view 设置任意圆角

实际开发中经常遇到圆角,并且很多时候不是在四周设置同样大小的圆角,为了提高开发效率,我封装了一个 CornerView

直接看效果:

代码拿走吧,伸手党:

import UIKit

@IBDesignable

class CornerView: 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()
    }
    
}


推荐阅读更多精彩内容