How to make a filling progress circle in iOS?

2019-06-02 13:55发布

问题:

I need to make a progress circle like this:

I have created a CAShapeLayer for the circle, and animate its strokeEnd property like this:

pieShape = CAShapeLayer()
pieShape.path = UIBezierPath(arcCenter: CGPointMake(29, 29), radius: 27.0, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true).CGPath
pieShape.fillColor = UIColor.clearColor().CGColor
pieShape.strokeColor = UIColor.blackColor().CGColor
pieShape.lineWidth = 4.0

self.layer.addSublayer(pieShape)


let countDownAnimation = CABasicAnimation(keyPath: "strokeEnd")
        countDownAnimation.duration = durationInSeconds
        countDownAnimation.removedOnCompletion = false
        countDownAnimation.fromValue = NSNumber(float: 0.0)
        countDownAnimation.toValue = NSNumber(float: 1.0)
        countDownAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
        self.pieShape.strokeStart = 1.0
        self.pieShape.addAnimation(countDownAnimation, forKey: "drawCircleAnimation")

But, this not what I want. I need to animate the circle filling, not only the border. Thank you.

回答1:

The easiest way is to cheat, and animate just the stroke, but make it appear to be animating the fill of the circle. For example, if you wanted a circle of radius 30, use a radius of 15 instead, but a lineWidth of 30, so that the stroke effectively covers from the center to the desired radius of 30.

There are more complicated methods using CADisplayLink, and updating it yourself, but the above is pretty easy way to achieve the desired effect.