如何为 UIView 添加圆角半径

How to add corner radius for UIView

我必须设置 UIView 的一些圆角半径,我通过以下代码设置它:

@IBDesignable
class MyUIviewCorner: UIView {

    override func layoutSubviews() { setup() } 

    func setup() {
        let r = self.bounds.size.height / 2
        let path = UIBezierPath(roundedRect: self.bounds,
        byRoundingCorners: [.topLeft, .topRight],
        cornerRadii: CGSize(width: r, height: r))
        let mask = CAShapeLayer()
        mask.backgroundColor = UIColor.clear.cgColor
        mask.path = path.cgPath
        layer.borderWidth = 1.5
        layer.borderColor = UIColor.red.cgColor
        self.layer.mask = mask
    }
}

但我得到了这个结果:

我不明白为什么顶角有空格?

如果我设置底角半径,我会得到:

你不应该为此使用掩码,你可以简单地使用 layer.maskedCorners 属性.

layer.cornerRadius = r
layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]

如果你增加边框宽度,你就会明白为什么:

好像还有一个填充的矩形"on top of"创建图层绘制的圆角矩形,遮住了圆角


你可以通过 UIBezierPaths 绘图来实现你想要的:

override func draw(_ rect: CGRect) {
    let r = self.bounds.size.height / 2
    let path = UIBezierPath(roundedRect: self.bounds,
    byRoundingCorners: [.topLeft, .topRight],
    cornerRadii: CGSize(width: r, height: r))
    path.lineWidth = 1.5
    UIColor.red.setStroke()
    path.stroke()
}