I have a CAShapeLayer which contains a CGPath. Using the built-in animation of iOS I can easily morph this path into another one using an animation:
CABasicAnimation *morph = [CABasicAnimation animationWithKeyPath:@"path"]; morph.fromValue = (id)myLayer.path; mayLayer.path = [self getNewPath]; morph.toValue = (id)myLayer.path; morph.duration = 0.3; [myLayer addAnimation:morph forKey:nil];
That works perfectly.
However, I'd now like to morph gradually between these paths during a drag operation. In order to do this I need to be able to retrieve the interpolated path at any point during the drag. Is there a way to ask iOS for this?
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.
As I said above, there is very little code involved in this little trick.
speed
of the layer (yes they conform to CAMediaTiming
) or the animation to 0.0timeOffset
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With