Tweening / Interpolating between two CGPaths / UIBeziers

試著忘記壹切 提交于 2019-12-17 06:23:10

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/18375822/tweening-interpolating-between-two-cgpaths-uibeziers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!