How to draw an animated path with multiple colors in ios?
I found a general solution that work very well. Since there is no way for drawing a unique path of different colors, then I just draw, without animation, all the paths of different colors that compound the path that I want. After that, I drawn an unique path in the reverse direction that cover all those paths, and apply an animation to this path.
For example, in the case above, I draw both arcs with the following code:
class CircleView: UIView {
let borderWidth: CGFloat = 20
let startAngle = CGFloat(Double.pi)
let middleAngle = CGFloat(Double.pi + Double.pi / 2)
let endAngle = CGFloat(2 * Double.pi)
var primaryColor = UIColor.red
var secondaryColor = UIColor.blue
var currentStrokeValue = CGFloat(0)
override func draw(_ rect: CGRect) {
let center = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
let radius = CGFloat(self.frame.width / 2 - borderWidth)
let path1 = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: middleAngle, clockwise: true)
let path2 = UIBezierPath(arcCenter: center, radius: radius, startAngle: middleAngle, endAngle: endAngle, clockwise: true)
path1.lineWidth = borderWidth
primaryColor.setStroke()
path1.stroke()
path2.lineWidth = borderWidth
secondaryColor.setStroke()
path2.stroke()
}
}
After that, I get path path3
and then I add it to a layer that will be added to the view:
var path3 = UIBezierPath(arcCenter: center, radius: radius, startAngle: endAngle, endAngle: startAngle, clockwise: true)
Note in this path that it covers the previous two path in the reverse order, since its startAngle is equal to the value of endAngle
, its endAngle is equal to startAngle
and the clockwise property is set to true
. This path is the one that I will go to animate.
For example, if I want to show the 40% of the whole (imaginary) path (the one composed by the paths of different colors), I translate that to show the 60% of my cover path path3
. The way in which we can animate path3
can be found in the link provided in the question.