rounded corners on NSView using NSBezierPath are drawn badly

2k views Asked by At

In my ViewController's main NSView, I override the func drawRect(dirtyRect: NSRect) method to implement rounded corners on my main view using NSBezierPath. In that same method I also designate the gradient background of my main view.

override func drawRect(dirtyRect: NSRect) {

    let path: NSBezierPath = NSBezierPath(roundedRect: self.bounds, xRadius: 18.0, yRadius: 18.0)
    path.addClip()

   let gradient = NSGradient(startingColor: NSColor(hexColorCode: "#383838"), endingColor: NSColor(hexColorCode: "#222222"))
   gradient.drawInRect(self.frame, angle: 90)
}

The problem that arises is illustrated in the following image:

The image shows one of the views corners. The rounding of corners is only partially successful, as there still remains a white corner sticking out beyond the window's rounded corners.

If anyone has a better method of setting a window's corner radius I would be open to such suggestions. I have done a lot of research on the matter, however this solution appears to be the simplest.

Any advice on how to fix this issue is greatly appreciated.

2

There are 2 answers

0
c-smile On BEST ANSWER

You should do the following on your NSWindow instance:

[window setOpaque:NO];
[window setBackgroundColor:[NSColor clearColor]];

and draw needed shape.

And check this article.

0
Luke Carbis On

I found a solution, by using a Sublayer.

class StyledButton: NSView {
    let roundLayer: CALayer = CALayer()

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        setup()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    func setup() {
        self.wantsLayer = true
        self.layer?.addSublayer(roundLayer)
        roundLayer.frame = self.bounds
        roundLayer.cornerRadius = 3
        roundLayer.backgroundColor = NSColor.redColor().CGColor
    }
}