Reputation: 551
I'm trying to animate drawing a circle with:
func drawProgressCircle(with endAngle: CGFloat) {
let progressBezierPath = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2, y: self.frame.width / 2), radius: self.frame.width / 2.5, startAngle: -CGFloat(Double.pi / 2), endAngle: endAngle, clockwise: true)
let progressShapeLayer = CAShapeLayer()
progressShapeLayer.path = progressBezierPath.cgPath
progressShapeLayer.strokeColor = UIColor.brown.cgColor
progressShapeLayer.fillColor = UIColor.clear.cgColor
progressShapeLayer.lineWidth = 15.0
// Do not draw initially. Wait for animation
progressShapeLayer.strokeEnd = 0.0
// Make corners rounded
progressShapeLayer.lineCap = kCALineCapRound
self.layer.addSublayer(progressShapeLayer)
self.animate(circleWith: progressShapeLayer, from: -CGFloat(Double.pi / 2), to: endAngle, with: 2.0)
}
and to animate it I call this function:
func animate(circleWith shapeLayer: CAShapeLayer, from: CGFloat, to: CGFloat, with duration: TimeInterval) {
// We want to animate the strokeEnd property of the circleLayer
let animation = CABasicAnimation(keyPath: "strokeEnd")
// Set the animation duration appropriately
animation.duration = duration
// Animate from start point to end point
animation.fromValue = from
animation.toValue = to
// Do a linear animation (i.e. the speed of the animation stays the same)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Set the circleLayer's strokeEnd property to 1.0 now so that it's the
// right value when the animation ends.
shapeLayer.strokeEnd = 1.0
// Do the actual animation
shapeLayer.add(animation, forKey: "animate")
}
but I do not know why it does not animate it. The canvas is empty and in 2 seconds it just appears on the canvas. Without any animation.
What is the problem? Why it does not animate drawing?
Upvotes: 1
Views: 273
Reputation: 1399
Replace the animation formValue & toValue by:
// Animate from start point to end point
animation.fromValue = 0
animation.toValue = 1
Basically the CABasicAnimation
for keyPath stroke
does not know that you are drawing a circle, it just animate from 0 to 1.
if you give the toValue
a value of 0.5 it will just animate to the half of the path.
it's unlike the CABasicAnimation
for keyPath position
which take CGPoint for the fromValue
and toValue
.
Upvotes: 1