Rounded corners on NSView using NSBezierPath draw poorly
In my main NSView ViewController, I am overriding a method func drawRect(dirtyRect: NSRect)
to implement rounded corners on my main view with NSBezierPath
. In the 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 occurs is illustrated in the following image:
The image shows one of the corners of the view. The rounding of the corners is only partially successful, as there is still a white corner sticking out of the window with the rounded corners.
If anyone has a better way of setting the window corner radius, I'd be open to suggestions like this. I've done a lot of research on this, however this solution seems to be the simplest.
Any advice on how to fix this issue is greatly appreciated.
source to share
In the NSWindow instance, you should do the following:
[window setOpaque:NO];
[window setBackgroundColor:[NSColor clearColor]];
and draw the required shape.
And check out this article .
source to share
I found a solution 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
}
}
source to share