Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...