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() } }
自律 平静 思考 实践