在 UIBezierPath 图形上应用渐变层

Applying gradient layer over a UIBezierPath graph

第一次提问,问得不是很透彻请见谅。

基本上我试图在绘制为图形的 UIBezierPath 之上应用渐变层。

这是我的图表:

这是我要使用的渐变层:

这是我尝试绘制的图形:

let path = quadCurvedPathWithPoints(points: points)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.position = CGPoint(x: 0, y: 0)
shapeLayer.lineWidth = 1.0

显然,这会用蓝色描边填充图表,但现在我正在尝试应用白色到绿色的渐变。我这样做的方式不起作用。这是结果:

这是我苦苦挣扎的代码:

let startColor = UIColor.white.withAlphaComponent(0.5)
let endColor = UIColor.green

let gradient = CAGradientLayer()
gradient.colors = [startColor.cgColor, endColor.cgColor]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.frame = path.bounds
let shapeMask = CAShapeLayer()
shapeMask.path = path.cgPath
gradient.mask = shapeLayer
sparkLineView.layer.addSublayer(gradient)

这是一个使用渐变绘制 UIBezierPath 路径的小演示。您可以将其复制到 Swift 游乐场。

class GradientGraph: UIView {
    override func draw(_ rect: CGRect) {
        // Create the "graph"
        let path = UIBezierPath()
        path.move(to: CGPoint(x: 0, y: frame.height * 0.5))
        path.addLine(to: CGPoint(x: frame.width * 0.2, y: frame.height * 0.3))
        path.addLine(to: CGPoint(x: frame.width * 0.4, y: frame.height * 0.8))
        path.addLine(to: CGPoint(x: frame.width * 0.6, y: frame.height * 0.4))
        path.addLine(to: CGPoint(x: frame.width * 0.8, y: frame.height * 0.7))

        // Create the gradient
        let gradient = CGGradient(colorsSpace: nil, colors: [UIColor.white.cgColor,UIColor.green.cgColor] as CFArray, locations: nil)!

        // Draw the graph and apply the gradient
        let ctx = UIGraphicsGetCurrentContext()!
        ctx.setLineWidth(6)

        ctx.saveGState()
        ctx.addPath(path.cgPath)
        ctx.replacePathWithStrokedPath()
        ctx.clip()
        ctx.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: frame.width, y: 0), options: [])
        ctx.restoreGState()
    }
}

let graph = GradientGraph(frame: CGRect(x: 0, y: 0, width: 700, height: 700))