我有一个 macOS 应用程序,可以在其中绘制线条和其他图形。
我使用 NSBezierPath 来形成线条或图形,然后将其添加到 CAShapeLayer 的路径中,最后将 CAShapeLayer 添加到视图中。
这一切都很好,我有一个单一的笔画颜色。但是,我希望线条/图形不是单一颜色,而是多种颜色(渐变)。我知道这可以通过 CAGradientLayer 完成,并尝试了其他 SO 问题中的一些示例,显示 iOS 变体,但它们对我不起作用。
以下是该应用程序的代码片段:
startPoint = point
currentPath = NSBezierPath()
currentShape = CAShapeLayer()
currentShape?.lineWidth = lineWeight
currentShape?.strokeColor = strokeColor.cgColor
currentShape?.fillColor = fillColor.cgColor
currentShape?.lineJoin = CAShapeLayerLineJoin.round
currentShape?.lineCap = CAShapeLayerLineCap.round
currentPath?.move(to: point)
currentPath?.line(to: point)
currentShape?.path = currentPath?.cgPath
view.layer?.addSublayer(currentShape!)
currentGradient = CAGradientLayer()
currentGradient?.mask = currentShape
currentGradient?.frame = currentShape!.frame
currentGradient?.colors = [NSColor.red.cgColor, NSColor.black.cgColor]
view.layer?.addSublayer(currentGradient!)
// some more code here that I omitted (to draw shapes with NSBezierPath)
if let shape = currentShape {
shape.path = currentPath?.cgPath
currentGradient?.mask = shape
currentGradient?.frame = shape.frame
}
如果我删除涉及的代码,currentGradient
那么我会看到线条/图形(一种纯色),但是当我添加渐变部分时,我什么也看不到。我在上面的代码中做错了什么?
任何帮助或提示将不胜感激。