What's the easiest way to animate a line?

天涯浪子 提交于 2019-12-04 06:50:27

Use CAShapeLayers, and a combination of CATransactions and CABasicAnimation.

You can add a given path to a shapeLayer and let it do the rendering.

A CAShapeLayer object has two properties called strokeStart and strokeEnd, which defines where along the path the end of the line should render. The defaults are 0.0 for strokeStart, and 1.0 for strokeEnd.

If you set up your path so that strokeEnd initially starts at 0.0, you will see no line.

You can then animate, from 0.0 to 1.0, the strokeEnd property and you will see the line lengthen.

To change CAShapeLayer's implicit 0.25s default animation timing, you can add a function to the class, like so:

-(void)animateStrokeEnd:(CGFloat)_strokeEnd {
    [CATransaction begin];
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:keyPath];
    animation.duration = 2.0f; //or however long you want it to happen
    animation.fromValue = [NSNumber numberWithFloat:self.strokeEnd]; // from the current strokeEnd value
    animation.toValue = [NSNumber numberWithFloat:_strokeEnd]; //to the end of the path
    [CATransaction setCompletionBlock:^{ self.strokeEnd = _strokeEnd }];
    [self addAnimation:animation forKey:@"animateStrokeEnd"];
    [CATransaction commit];
}

You can pass any value from 0.0f to 1.0f as the value of _strokeEnd.

The setCompletionBlock: ensures that the value you are passing is explicitly set after the animation completes.

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