I need to draw something like the following image in my iOS app, except that the arc may contain more colors:
I know how to draw it, but I'm looking for a way to animate the drawing of the path.
There is a similar question here, except that the circle is not animated. This is another question where it's explained how to animate a circle, and it work ok in my case, except that it doesn't handle multiple colors in the path.
How can accomplish this?
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:
After that, I get path
path3
and then I add it to a layer that will be added to the view: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 tostartAngle
and the clockwise property is set totrue
. 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 animatepath3
can be found in the link provided in the question.@Reynaldo Aguilar 's answer works well. You can achieve the same thing by creating a mask layer and animating its frame. The benefit of this approach is that it works with any (and multi-colored) background. The downside to this approach is that it may not work if the line is not functional, since multiple points could be hidden/revealed at the same time (when you only want one of them to be) in that scenario.
For ease of use, you can subclass UIView and override its draw and init methods like so to add the lines.
INIT:
DRAW:
You can then have a function to animate the mask layer like so
ANIMATE:
With the subclass, implementation is easy. Initialize it, add it as a subview to where you want, and then call animate() when you want the animation to begin. You can also fiddle with other things, like the alphas during initialization and animation, if you want the drawings to be hidden to start.