簡體   English   中英

動畫CAShapeLayer

[英]Animation CAShapeLayer

我用這段代碼畫了一個圖:

CAShapeLayer *curentGraph = [CAShapeLayer new];
CGMutablePathRef linePath = CGPathCreateMutable();
curentGraph.lineWidth = 3.0f;
curentGraph.fillColor = [[UIColor clearColor] CGColor];
curentGraph.strokeColor = [colorGraph CGColor];
for (NSValue *value in arrOfPoints) {
    CGPoint pt = [value CGPointValue];
    CGPathAddLineToPoint(linePath, NULL, pt.x,pt.y);
};
curentGraph.path = linePath;CGPathRelease(linePath);
[self.layer addSublayer:curentGraph];

它看起來像這樣

圖表截圖

但我有一個問題。 我需要為圖形顯示動畫。 每個點應該從位置y = 0向上移動到y = pt.y 就像他們在本網站的圖表中所做的那樣。

如何為我的圖形設置動畫?

CAShapeLayer上的path屬性是可動畫的。 這意味着您可以創建一個路徑,其中每個y值為0.0並且從該路徑到實際圖形的動畫。 只需確保路徑具有相同的點數。 這應該很簡單,因為你已經有了循環。

CGMutablePathRef startPath = CGPathCreateMutable();
for (NSValue *value in arrOfPoints) {
    CGPoint pt = [value CGPointValue];
    CGPathAddLineToPoint(startPath, NULL, pt.x, 0.0);
}

然后,您可以通過為@"path"鍵創建CABasicAnimation來為路徑設置動畫。

CABasicAnimation *pathAppear = [CABasicAnimation animationWithKeyPath:@"path"];
pathAppear.duration = 2.0; // 2 seconds
pathAppear.fromValue = (__bridge id)startPath;
pathAppear.toValue   = (__bridge id)linePath;

[yourShapeLayer addAnimation:pathAppear forKey:@"make the path appear"];

這是一個CAShapeLayer子類,它允許您隱式地為其path設置動畫(無需聲明CABasicAnimation ):

接口:

@interface CAShapeLayerAnim : CAShapeLayer
@end

執行:

@implementation CAShapeLayerAnim

- (id<CAAction>)actionForKey:(NSString *)event {
    if ([event isEqualToString:@"path"]) {
        CABasicAnimation *animation = [CABasicAnimation
            animationWithKeyPath:event];
        animation.duration = [CATransaction animationDuration];
        animation.timingFunction = [CATransaction
            animationTimingFunction];
        return animation;
    }
   return [super actionForKey:event];
}

@end

對於動畫,您需要使用strokeStartstrokeEnd屬性。

請參閱Ole Begemann博客文章中的示例CAShapeLayer動畫。

從文檔strokeStart

此屬性的值必須在0.0到1.0的范圍內。 此屬性的默認值為1.0。

結合strokeEnd屬性,此屬性定義筆划路徑的子區域。 此屬性中的值表示沿strokeEnd屬性定義結束點時開始描邊的路徑的相對點。 值0.0表示路徑的開頭,而值1.0表示路徑的結尾。 其間的值沿路徑長度線性解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM