Reynaldo Aguilar Reynaldo Aguilar - 1 year ago 140
iOS Question

How to draw an animated path with multiple colors in ios?

I need to draw something like the following image in my iOS app, except that the arc may contain more colors:

Path to draw

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?

Answer Source

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(M_PI)
    let middleAngle = CGFloat(M_PI + M_PI / 2)
    let endAngle = CGFloat(2 * M_PI)
    var primaryColor = UIColor.redColor()
    var secondaryColor = UIColor.blueColor()
    var currentStrokeValue = CGFloat(0)

    override func drawRect(rect: CGRect) {

        var center = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
        var radius = CGFloat(self.frame.width / 2 - borderWidth)

        var path1 = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: middleAngle, clockwise: true)

        var path2 = UIBezierPath(arcCenter: center, radius: radius, startAngle: middleAngle, endAngle: endAngle, clockwise: true)

        path1.lineWidth = borderWidth
        path2.lineWidth = borderWidth

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download