0

I've read some topics about but can't apply to me... I try to apply a gradient color to an arc drawed with a UIBezierPath. The problem is that my gradient fill all the circle and not just the ring.

func layerWith(size: CGSize, color: UIColor) -> CALayer {
    let layer: CAShapeLayer = CAShapeLayer()
    var path: UIBezierPath = UIBezierPath()
    let lineWidth: CGFloat = 2

    layer.backgroundColor = nil
    layer.path = path.cgPath
    layer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)


    switch self {
    case .ring:
        path.addArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2),
                    radius: size.width / 2,
                    startAngle: 0,
                    endAngle: CGFloat(2 * M_PI),
                    clockwise: false);

        layer.fillColor =  UIColor.clear.cgColor
        layer.strokeColor = color.cgColor
        layer.lineWidth = lineWidth

        let colorGradStart  = UIColor(red: 0/255, green: 209/255, blue: 192/255, alpha: 1.0)
        let colorGradEnd = UIColor(red: 00/255, green: 99/255, blue: 91/255, alpha: 1.0)

        let gradient = CAGradientLayer()
        gradient.frame = path.bounds
        gradient.colors = [colorGradStart.cgColor, colorGradEnd.cgColor]

        let shapeMask = CAShapeLayer()
        shapeMask.path = path.cgPath
        gradient.mask = shapeMask


        layer.addSublayer(gradient)
    }
    return layer
}

So this code, apply the gradient to all the filled form, me i just need the arc.

John
  • 11
  • 1

2 Answers2

0

One way to do it is to apply your CAShapeLayer to your gradient layer as a mask. Then it reveals the gradient.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

You should set shapeMask's fillColor and strokeColor, not the layer.

Simon
  • 1
  • 1