iOS 實現視圖指定圓角
需求
- 可以設置單獨設置視圖的某個圓角
- 可以設置幾個指定的圓角
- 可以設置是否繪制邊框、邊框寬度
實現原理
使用貝塞爾曲線實現
代碼
由于不是很復雜,所以就直接貼上代碼
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() } }
自律 平靜 思考 實踐
浙公網安備 33010602011771號