Tweening / Interpolating between two CGPaths / UIBeziers
This is actually a lot simpler then you would first think and uses animations with "no" speed (paused). Now with the paused animation added to the layer you can change the time offset to jump to a specific time within the animation.
If you are not planning on running the animation by itself (i.e. only control it manually) I would suggest that you change the duration of the animation to 1. This means that you change the time offset from 0 to 1 when moving from 0% to 100%. If your duration was 0.3 (as in your example) then you would set the time offset to a value between 0 and 0.3 instead.
Implementation
As I said above, there is very little code involved in this little trick.
- (Optional) Set the duration to 1.0
- Set the
speed
of the layer (yes they conform toCAMediaTiming
) or the animation to 0.0 - During the drag gesture or slider (as in my example) set the
timeOffset
of the layer or animation (depending on what you did in step 2).
This is how I configured my animation + shape layer
CABasicAnimation *morph = [CABasicAnimation animationWithKeyPath:@"path"];
morph.duration = 1.; // Step 1
morph.fromValue = (__bridge id)fromPath;
morph.toValue = (__bridge id)toPath;
[self.shapeLayer addAnimation:morph forKey:@"morph shape back and forth"];
self.shapeLayer.speed = 0.0; // Step 2
And the slider action:
- (IBAction)sliderChanged:(UISlider *)sender {
self.shapeLayer.timeOffset = sender.value; // Step 3
}
You can see the end result below. Happy coding!