Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rounded corners on NSView using NSBezierPath are drawn badly

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.

like image 980
Jonathan H. Avatar asked Jun 20 '15 03:06

Jonathan H.


2 Answers

You should do the following on your NSWindow instance:

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

and draw needed shape.

And check this article.

like image 160
c-smile Avatar answered Nov 09 '22 20:11

c-smile


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
    }
}
like image 37
Luke Carbis Avatar answered Nov 09 '22 20:11

Luke Carbis