我正在创建一个应用程序,它涉及随着时间的推移在工作区内设置动画线条。我目前的做法是在 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。我对此有什么选择?我需要让它执行得更快,并且很想摆脱这个笨重的计时器。
谢谢!
最佳答案
使用 CAShapeLayers,以及 CATransactions 和 CABasicAnimation 的组合。
您可以将给定路径添加到 shapeLayer 并让它进行渲染。
一个 CAShapeLayer 对象有两个属性,分别是 strokeStart
和 strokeEnd
,它们定义了线条末端应该沿着路径呈现的位置。 strokeStart
的默认值为 0.0,strokeEnd
的默认值为 1.0。
如果您设置路径,使 strokeEnd
最初从 0.0 开始,您将看不到任何线条。
然后您可以为 strokeEnd
属性设置动画,从 0.0 到 1.0,您将看到线条变长。
要更改 CAShapeLayer 的隐式 0.25 秒默认动画时间,您可以向该类添加一个函数,如下所示:
-(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:
确保您传递的值在动画完成后明确设置。
关于objective-c - 制作线条动画的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6773185/