I'm trying for hours to draw a gradient border on an NSView, like this.
I've adjusted to code to NSView:
class BlurView: NSView {
override init(frame: CGRect) {
super.init(frame: frame)
let gradient = CAGradientLayer()
gradient.frame = CGRect(origin: CGPoint.zero, size: frame.size)
gradient.colors = [NSColor.blue.cgColor, NSColor.green.cgColor, NSColor.blue.cgColor]
let shape = CAShapeLayer()
shape.lineWidth = 2
shape.path = NSBezierPath(rect: self.bounds).cgPath
shape.strokeColor = NSColor.black.cgColor
shape.fillColor = NSColor.clear.cgColor
gradient.mask = shape
self.wantsLayer = true
self.layer?.insertSublayer(gradient, at: 0)
}
}
However it doesn't work, I cannot find more info online, so maybe this is only working for iOS. A couple of things of interest:
- self.bounds prints (0.0, 0.0, 0.0, 0.0) so I don't think that is working properly
- I added the cgPath as an extension on NSBeziertPath with the following code
import Foundation
extension NSBezierPath {
public var cgPath: CGPath {
let path = CGMutablePath()
var points = [CGPoint](repeating: .zero, count: 3)
for i in 0 ..< elementCount {
let type = element(at: i, associatedPoints: &points)
switch type {
case .moveTo:
path.move(to: points[0])
case .lineTo:
path.addLine(to: points[0])
case .curveTo:
path.addCurve(to: points[2], control1: points[0], control2: points[1])
case .closePath:
path.closeSubpath()
@unknown default:
continue
}
}
return path
}
}
Any idea how to get this working?