Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 712
Reynaldo Aguilar Avatar asked Jun 09 '15 16:06

Reynaldo Aguilar


1 Answers

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.

like image 127
Reynaldo Aguilar Avatar answered Sep 30 '22 17:09

Reynaldo Aguilar