What is the easiest way to animate a line?

I am creating an application that animates strings in the workspace over time. My current approach for this is to use code like this in drawRect :

 CGContextSetStrokeColor(context, black); CGContextBeginPath(context); CGContextMoveToPoint(context, startPoint.x, startPoint.y); CGContextAddLineToPoint(context, finalPoint.x, finalPoint.y); CGContextStrokePath(context); 

... and then just set a timer to start every 0.05 seconds to update finalPoint and call setNeedsDisplay .

I find this approach (when 5ish lines move right away) slows down the app terribly, and even with such a high refresh rate it still seems jerky.

There should be a better way to do this very simple line drawing in an animated line, that is, say that I want the line to start with x1, y1 and stretch to x2, y2 over a certain period of time. What are my options for this? I need to do it faster and would like to get rid of this awkward timer.

Thanks!

+6
source share
1 answer

Use CAShapeLayers and a combination of CATransactions and CABasicAnimation.

You can add this path to the shapeLayer element and let it render.

The CAShapeLayer object has two properties called strokeStart and strokeEnd , which determines where along the path that the end of the line should execute. Default values: 0.0 for strokeStart and 1.0 for strokeEnd .

If you set your path so that strokeEnd initially strokeEnd with 0.0, you will not see the line.

Then you can animate from 0.0 to 1.0, the strokeEnd property, and you will see that the line lengthens.

To change the CAShapeLayer implicit default 0.25-second animation time, you can add a function to the class, for example:

 -(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 .

setCompletionBlock: ensures that the value you setCompletionBlock: is explicitly set after the animation finishes.

+5
source

Source: https://habr.com/ru/post/893242/


All Articles