How to animate the drawing of a CGPath?

后端 未结 2 1818
离开以前
离开以前 2021-02-05 23:58

I am wondering if there is a way to do this using Core Animation. Specifically, I am adding a sub-layer to a layer-backed custom NSView and setting its delegate to another custo

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 00:11

    I found this animated paths example and wanted to share it for anyone else looking for how to do this with some code examples.

    You will be using CAShapeLayer's strokeStart and strokeEnd which requires sdk 4.2, so if you are looking to support older iOS SDKs unfortunately this isn't what you want.

    The really nice thing about these properties is that they are animatable. By animating strokeEnd from 0.0 to 1.0 over a duration of a few seconds, we can easily display the path as it is being drawn:

    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 10.0;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    [self.pathLayer addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
    

    Finally, add a second layer containing the image of a pen and use a CAKeyframeAnimation to animate it along the path with the same speed to make the illusion perfect:

    CAKeyframeAnimation *penAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    penAnimation.duration = 10.0;
    penAnimation.path = self.pathLayer.path;
    penAnimation.calculationMode = kCAAnimationPaced;
    [self.penLayer addAnimation:penAnimation forKey:@"penAnimation"];
    

    Which the source can be viewed here and a demo video here. Read the creators blog for more information.

提交回复
热议问题