我花了几个小时在NSView上画一个渐变边框,like this。
我已经调整到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)
}
}
但是它不起作用,我不能在网上找到更多的信息,所以也许这只适用于iOS。有几件有趣的事:
- self.bounds打印(0.0,0. 0,0. 0,0.0)所以我不认为这是正确的工作
- 我使用以下代码添加了cgPath作为NSBeziertPath的扩展
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
}
}
你知道怎么让它工作吗?
1条答案
按热度按时间qltillow1#
我把它修好了。问题不在于我如何渲染边界,而在于如何管理视图。这是一个嵌入在react-native中的组件,因此它被初始化为0大小,并且只在以后更新。因此,渲染边框的回调需要在update方法中: