-3

我有一个 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那么我会看到线条/图形(一种纯色),但是当我添加渐变部分时,我什么也看不到。我在上面的代码中做错了什么?

任何帮助或提示将不胜感激。

4

1 回答 1

1

如果你搜索过,那么你就知道答案了。您不能使用渐变来描边形状。相反,您使用渐变蒙版;形状层变成了遮罩,从而显示了渐变层。示例(v是窗口中的视图):

    let grad = CAGradientLayer()
    grad.frame = v.bounds
    v.layer?.addSublayer(grad)
    grad.colors = [NSColor.red.cgColor, NSColor.blue.cgColor]
    let shape = CAShapeLayer()
    shape.frame = v.bounds
    shape.lineWidth = 3
    shape.fillColor = NSColor.clear.cgColor
    shape.strokeColor = NSColor.black.cgColor
    let path = CGPath(ellipseIn: v.bounds.insetBy(dx: 4, dy: 4), transform: nil)
    shape.path = path
    grad.mask = shape

在此处输入图像描述

于 2020-05-09T18:10:33.413 回答