0
votes

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

2
Do you just want a red rectangle with top corners rounded? - Sweeper
yes I do Sweeper - gianni rodari
See my answer here stackoverflow.com/a/46408735/5575955 124 useful vote from users... - Fabio

2 Answers

1
votes

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

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

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