简体   繁体   中英

How to add corner radius for UIView

I have to set some corner radius of UIView and I set it by this code:

@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
    }
}

But I get this result:

顶角半径

I don't understand why is there white spaces on the top corners?

If I set bottom corner radius I get this:

底角半径

You shouldn't use a mask for this, you can simply use the layer.maskedCorners property.

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

You can kind of see why if you increase the border width:

在此处输入图片说明

There seems to still be a filled rectangle "on top of" the rounded rectangle drawn by the created layer, covering up the rounded corner.


You can achieve what you want by just drawing with UIBezierPath s:

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM