'How to make a gradient circular path in Swift

I want to create a gradient circular path like the following image:

enter image description here

and I have the following code:

    circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
    outerTrackShapeLayer = CAShapeLayer()
    outerTrackShapeLayer.path = circularPath.cgPath
    outerTrackShapeLayer.position = position
    outerTrackShapeLayer.strokeColor = outerTrackColor.cgColor
    outerTrackShapeLayer.fillColor = UIColor.clear.cgColor
    outerTrackShapeLayer.lineWidth = lineWidth
    outerTrackShapeLayer.strokeEnd = 1
    outerTrackShapeLayer.lineCap = CAShapeLayerLineCap.round
    outerTrackShapeLayer.transform = rotateTransformation
    addSublayer(outerTrackShapeLayer)

    innerTrackShapeLayer = CAShapeLayer()
    innerTrackShapeLayer.strokeColor = innerTrackColor.cgColor
    innerTrackShapeLayer.position = position
    innerTrackShapeLayer.strokeEnd = progress
    innerTrackShapeLayer.lineWidth = lineWidth
    innerTrackShapeLayer.lineCap = CAShapeLayerLineCap.round
    innerTrackShapeLayer.fillColor = UIColor.clear.cgColor
    innerTrackShapeLayer.path = circularPath.cgPath
    innerTrackShapeLayer.transform = rotateTransformation
    let gradient = CAGradientLayer()
    gradient.frame = circularPath.bounds
    gradient.colors = [UIColor.magenta.cgColor, UIColor.cyan.cgColor]
    gradient.position = innerTrackShapeLayer.position
    gradient.mask = innerTrackShapeLayer
    addSublayer(gradient)

but it doesn't work correctly, you can see the result in the following image:

enter image description here

I would appreciate if someone help me, thanks.



Solution 1:[1]

It looks like the gradient layer frame is set equal to the path frame which doesn't include the thickness of the stroke of the CAShapeLayer which is why it is cut off in a square. I can't see from the code whether you have the circular path on a subview but if you set the gradient frame to the same as the subview frame that should sort the cut off out as well as the misalignment of the progress view on the track.

Hope that helps.

Solution 2:[2]

I also face this issue and fixed it by changing the radius value as my radius value was larger than the expected

In circularPath, you need to make sure that your radius value should not be larger than the following

let radius = (min(width, height) - lineWidth) / 2

circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rab
Solution 2 DharmanBot