Add gradient to CAShapeLayer

1.1k Views Asked by At

I got this CAShapeLayer drawing a line in a chart for me:

open func generateLayer(path: UIBezierPath) -> CAShapeLayer {
    let lineLayer = CAShapeLayer()
    lineLayer.lineJoin = lineJoin.CALayerString
    lineLayer.lineCap = lineCap.CALayerString
    lineLayer.fillColor = UIColor.clear.cgColor
    lineLayer.lineWidth = lineWidth
    lineLayer.strokeColor = lineColors.first?.cgColor ?? UIColor.white.cgColor

    lineLayer.path = path.cgPath

    if dashPattern != nil {
        lineLayer.lineDashPattern = dashPattern as [NSNumber]?
    }

    if animDuration > 0 {
        lineLayer.strokeEnd = 0.0
        let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
        pathAnimation.duration = CFTimeInterval(animDuration)
        pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        pathAnimation.fromValue = NSNumber(value: 0 as Float)
        pathAnimation.toValue = NSNumber(value: 1 as Float)
        pathAnimation.autoreverses = false
        pathAnimation.isRemovedOnCompletion = false
        pathAnimation.fillMode = kCAFillModeForwards

        pathAnimation.beginTime = CACurrentMediaTime() + CFTimeInterval(animDelay)
        lineLayer.add(pathAnimation, forKey: "strokeEndAnimation")

    } else {
        lineLayer.strokeEnd = 1
    }

    return lineLayer
}

Now I'd like to draw this line with a gradient instead of a single color. This is what I came up with, but unfortunately it does not draw the line for me. Without this added code (lineColors.count == 1) the line is drawn correctly with a single color.

fileprivate func show(path: UIBezierPath) {
    let lineLayer = generateLayer(path: path)
    layer.addSublayer(lineLayer)

    if lineColors.count > 1 {
        let gradientLayer = CAGradientLayer()
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        gradientLayer.frame = self.bounds
        gradientLayer.colors = lineColors
        gradientLayer.mask = lineLayer
        layer.addSublayer(gradientLayer)
    }
}
1

There are 1 best solutions below

0
dehlen On

Well turns out I was searching more than an hour for this line:

gradientLayer.colors = lineColors

I forgot to map the UIColors objects in this array to CGColorRef objects... This line fixed it for me:

gradientLayer.colors = lineColors.map({$0.cgColor})