Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tweening / Interpolating between two CGPaths / UIBeziers

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?

like image 247
tarmes Avatar asked Aug 22 '13 08:08

tarmes


1 Answers

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.

  1. (Optional) Set the duration to 1.0
  2. Set the speed of the layer (yes they conform to CAMediaTiming) or the animation to 0.0
  3. 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!

enter image description here

like image 95
David Rönnqvist Avatar answered Oct 05 '22 09:10

David Rönnqvist