AnimatedPath explores using the CAMediaTiming
protocol to interactively control the drawing of a path.
CAShapeLayer
with speed == 0
.strokeEnd
key path with a fromValue
of 0 and a toValue
of 1.speed == 0
, adjusting the layer's timeOffset
controls the time at which the animation is rendered.timeOffset
.The most difficult part of putting this example together was understanding how to add the animation to the layer and still be able to control the animation's progress via the timeOffset
. Here's what worked:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:NSStringFromSelector(@selector(strokeEnd))];
animation.fromValue = @0.0;
animation.toValue = @1.0;
animation.removedOnCompletion = NO;
animation.duration = kDuration;
[self.pathBuilderView.pathShapeView.shapeLayer addAnimation:animation forKey:NSStringFromSelector(@selector(strokeEnd))];
self.pathBuilderView.pathShapeView.shapeLayer.speed = 0;
self.pathBuilderView.pathShapeView.shapeLayer.timeOffset = 0.0;
[CATransaction flush];
self.pathBuilderView.pathShapeView.shapeLayer.timeOffset = kInitialTimeOffset;
The end result of this approach is that the animation has a beginTime
of 0 and the shape layer renders it at time kInitialTimeOffset
.
The [CATransaction flush]
is required because it forces the system to give the animation added to the layer a beginTime
. The animation's beginTime
is calculated by adding its initial value (its value before being added to the layer) to the layer's current time. This is why the layer's timeOffset
must be set to 0 rather than kInitialTimeOffset
when the animation is added. Otherwise, the animation's beginTime
will have already taken kInitialTimeOffset
into account such that the animation is added to the time range (kInitialTimeOffset, kInitialTimeOffset + kDuration)
instead of (0, kDuration)
.