什么是最简单的绘制动画线条的方法?

6

我正在创建一个涉及在工作区内随时间动画化线条的应用程序。 我目前的方法是使用像这样的代码在drawRect中:

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

然后只需设置一个计时器,每0.05秒更新finalPoint并调用setNeedsDisplay即可。

当有5条以上的线同时移动时,我发现这种方法会严重拖慢应用程序,即使刷新频率很高,仍然会出现卡顿。

肯定有更好的方法来执行这个非常简单的线性绘制动画 - 即说我想要一条线从x1,y1开始,延伸到x2,y2,在给定的时间内完成。我有哪些选择?我需要让它运行得更快,并且希望摆脱这个笨重的计时器。

谢谢!

1个回答

5
使用CAShapeLayers,结合CATransactions和CABasicAnimation技术,可以实现路径动画。
你可以将一个给定的路径添加到shapeLayer中,让它进行渲染。
CAShapeLayer对象有两个属性,分别为strokeStart和strokeEnd,用于定义线条在路径上的起始点和终止点。默认值为0.0和1.0。
如果将路径设置成strokeEnd初始值为0.0,那么就不会看到线条。
然后,你可以通过动画将strokeEnd属性从0.0变为1.0,这样就能看到线条逐渐延长。
如果想要改变CAShapeLayer的默认动画时间(0.25s),可以在该类中添加一个函数。
-(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];
}

您可以将从0.0f到1.0f的任何值作为_strokeEnd的值传递。

setCompletionBlock:确保在动画完成后显式设置传递的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接