3

我成功地爲單個圖層創建動畫,以沿着屏幕上的任意路徑改變其位置。我現在試圖複製這個動畫多次,以給出彎曲的東西幻覺。我把代碼放在一個CATransaction中,並把它放在一個循環中,增加循環的每次迭代的開始位置,然後在循環之後提交CATransaction。如果代碼不在循環中(即,只有一層被動畫),則看到的效果是相同的,然後在動畫結束時出現所有圖層(在我的委託在animationDidStop中的動畫結束時將其刪除之前)如何成功動畫多個CALayers?

我寫的代碼如下所示:

NSArray* path = [board caclulatePath:s]; 
    [CATransaction begin]; 
    [CATransaction setValue:[NSNumber numberWithFloat:([path count] * 0.25)] forKey:kCATransactionAnimationDuration]; 
    for (int i = 0; i < 20; i++) 
    { 
     CALayer* laserLayer = [CALayer layer]; 
     laserLayer.bounds = CGRectMake(s.frame.origin.x, s.frame.origin.y + (10*i), 20, 10); 
     laserLayer.position = CGPointMake(s.frame.origin.x + (s.frame.size.width/2), s.frame.origin.y + (s.frame.size.height/2) + (10*i)); 
     laserLayer.contents = (id)[UIImage imageNamed:@"Laser.png"].CGImage; 
     [self.layer addSublayer:laserLayer]; 

     CAKeyframeAnimation* anim = [CAKeyframeAnimation animationWithKeyPath:@"position"]; 
     anim.values = path; 
     anim.duration = ([path count] * 0.25); 
     anim.removedOnCompletion = NO; 
     anim.delegate = self; 
     anim.rotationMode = kCAAnimationRotateAuto; 
     [anim setValue:@"Fire" forKey:@"Action"]; 
     [anim setValue:laserLayer forKey:@"Layer"]; 
     [laserLayer addAnimation:anim forKey:nil]; 
    } 
    [CATransaction commit]; 

其中[板caclulatePath:s]的返回表示CGPoints NSValues的一個NSArray *。

我怎樣才能達到我以後的效果(這是同一路徑下的多個laser.png副本)? [Laser.png是20像素×20像素的紅色正方形];

回答

2

實際的問題是,每一層都跟着相同的路徑,在同一時間......解決方案是在延遲(someSmallFractionOfTime * i)之後將每個層/動畫開火,其中我增加了。

所以我提取的動畫部分作爲新的函數/方法/消息(無論它叫)

- (void) kickoffLaserAnimationWithPath: (NSArray *) path { 
CGPoint start = [(NSValue*)[path objectAtIndex:0] CGPointValue]; 
CALayer* laserLayer = [CALayer layer]; 
laserLayer.bounds = CGRectMake(start.x, start.y, 20, 10); 
laserLayer.position = CGPointMake(start.x, start.y); 
laserLayer.contents = (id)[UIImage imageNamed:@"Laser.png"].CGImage; 
[self.layer addSublayer:laserLayer]; 

CAKeyframeAnimation* anim = [CAKeyframeAnimation animationWithKeyPath:@"position"]; 
anim.values = path; 
anim.duration = ([path count] * laserSpeed); 
anim.removedOnCompletion = NO; 
anim.delegate = self; 
anim.rotationMode = kCAAnimationRotateAuto; 
[anim setValue:@"Fire" forKey:@"Action"]; 
[anim setValue:laserLayer forKey:@"Layer"]; 
[laserLayer addAnimation:anim forKey:nil]; 
isAnimating = YES; 

} 

和循環中調用它,如下所示:

NSArray* path = [board caclulatePath:s]; 
    [CATransaction begin]; 
    [CATransaction setValue:[NSNumber numberWithFloat:([path count] * laserSpeed)] forKey:kCATransactionAnimationDuration]; 
    float numBetweenPoints = (float)((float)s.frame.size.height/(float)10) * 2; 
    float delay = (laserSpeed/numBetweenPoints); 
    for (int i = 0; i < [path count]; i++) 
    { 
     [self performSelector:@selector(kickoffLaserAnimationWithPath:) withObject:path afterDelay:(delay*i)]; 

    } 
    [CATransaction commit]; 

瞧...

2

看一看CAAnimationGroup。我認爲這可能適合你的問題。

+1

將此+1這是值得一看的東西,雖然它沒有幫助我的問題... –