gianni rodari
gianni rodari

Reputation: 137

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:

top corner radius

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

If I set bottom corner radius I get this:

bottom corner radius

Upvotes: 1

Views: 817

Answers (2)

Sweeper
Sweeper

Reputation: 270758

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

enter image description here

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

Upvotes: 0

Eilon
Eilon

Reputation: 2982

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

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

Upvotes: 2

Related Questions