iOS 實現檢視指定圓角

sims發表於2024-07-04

需求

  • 可以設定單獨設定檢視的某個圓角
  • 可以設定幾個指定的圓角
  • 可以設定是否繪製邊框、邊框寬度

實現原理

使用貝塞爾曲線實現

程式碼

由於不是很複雜,所以就直接貼上程式碼

import UIKit

@IBDesignable
public class CornerView: UIView {

    @IBInspectable public var drawBorder: Bool = false
    @IBInspectable public var borderWidth: CGFloat = 1.0
    @IBInspectable public var topCornerRadius: CGFloat = 10.0
    @IBInspectable public var topLeft: Bool = false
    @IBInspectable public var topRight: Bool = false
    @IBInspectable public var bottomLeft: Bool = false
    @IBInspectable public var bottomRight: Bool = false
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    public override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        var corners: UInt = 0
        if self.topLeft == true {
            corners = corners | UIRectCorner.topLeft.rawValue
        }
        
        if self.topRight == true {
            corners = corners | UIRectCorner.topRight.rawValue
        }
        
        if self.bottomRight == true {
            corners = corners | UIRectCorner.bottomRight.rawValue
        }
        
        if self.bottomLeft == true {
            corners = corners | UIRectCorner.bottomLeft.rawValue
        }
        
        let topCorner: UIRectCorner = UIRectCorner(rawValue: corners)
        
        // 繪製圓角
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: topCorner, cornerRadii: CGSize(width: self.topCornerRadius, height: self.topCornerRadius))
        let maskLayer = CAShapeLayer()
        
        maskLayer.frame = self.bounds
        maskLayer.path = path.cgPath
        
        if drawBorder == true {
            // 繪製邊框
            UIBezierPath.drawRightTopCornerBorder(width: self.width, cornerRadius: self.topCornerRadius, lineWidth: self.borderWidth, cornerColor: .white)
            UIBezierPath.drawLeftTopCornerBorder(cornerRadius: self.topCornerRadius, lineWidth: self.borderWidth, cornerColor: .white)
        }
        
        self.layer.mask = maskLayer
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}

相關文章