[英]What's the easiest way to animate a line?
我正在創建一個應用程序,該應用程序涉及隨着時間的推移在工作區中設置動畫線。 我目前的方法是在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 object 有兩個屬性,稱為strokeStart
和strokeEnd
,它們定義了線的末端應該沿着路徑渲染的位置。 strokeStart 的默認值為 0.0, strokeStart
的默認strokeEnd
1.0。
如果您設置路徑,使strokeEnd
最初從 0.0 開始,您將看不到任何線條。
然后,您可以從 0.0 到 1.0 為strokeEnd
屬性設置動畫,您將看到線條變長。
要更改 CAShapeLayer 的隱式 0.25s 默認 animation 時序,可以將 function 添加到 class 中,如下所示:
-(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:
確保在 animation 完成后顯式設置您傳遞的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.