2011-10-07 275 views
3

我旋轉CALayer使用CABasicAnimation並正常工作。問題是,當我嘗試旋轉同一圖層時,它會在旋轉之前返回到其原始位置。我的預期結果是,對於下一輪,它應該從結束的地方開始。這裏是我的代碼:CABasicAnimation旋轉返回到原來的位置

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; 
animation.fromValue   = 0; 
animation.toValue   = [NSNumber numberWithFloat:3.0]; 
animation.duration   = 3.0; 
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; 
animation.removedOnCompletion = NO; 
animation.fillMode   = kCAFillModeForwards; 
animation.autoreverses  = NO; 
[calayer addAnimation:animation forKey:@"rotate"]; 

我的代碼有什麼缺失?謝謝

回答

16

發生什麼事情是,你看到表示層中的動畫。但是,這並不會更新圖層的實際位置。所以,一旦動畫完成,您會看到該圖層,因爲它沒有改變。

確實值得一讀"Core Animation Rendering Architecture"。否則,這可能會非常混亂。

[animation setDelegate:self];

然後,創建設置動畫完成時,你希望你的目標屬性的方法:

爲了解決這個問題,如下設置委託給你的CABasicAnimation。現在,這是令人困惑的部分。您應該在animationDidStart而不是animationDidStop上執行此操作。否則,表示層動畫將完成,當您看到calayer處於原始位置時,您將看到閃爍,然後它會跳躍(無動畫)到目標位置。試試animationDidStop,你會明白我的意思。

我希望這不是太混亂!

- (void)animationDidStart:(CAAnimation *)theAnimation 
{ 
    [calayer setWhateverPropertiesExpected]; 
} 

編輯:

我後來發現,蘋果推薦一個更好的方法來做到這一點。

奧列格Begemann具有正確的技術的一個很好的說明在他的博客Prevent Layers from Snapping Back to Original Values When Using Explicit CAAnimations

基本上你要做的就是啓動動畫之前,你先記下層的電流值,即,原始值:

// Save the original value 
CGFloat originalY = layer.position.y; 

接下來,設置toValue該層的模型。因此,層模型具有的你即將做任何動畫終值:

// Change the model value 
layer.position = CGPointMake(layer.position.x, 300.0); 

然後,設置動畫了動畫fromValue在於,你上面提到的原始值:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.y"]; 

// Now specify the fromValue for the animation because 
// the current model value is already the correct toValue 
animation.fromValue = @(originalY); 
animation.duration = 1.0; 

// Use the name of the animated property as key 
// to override the implicit animation 
[layer addAnimation:animation forKey:@"position"]; 

注以上編輯的代碼是複製/奧萊Begemann的博客粘貼爲清楚起見

+0

你將如何與諸如transform.rotation.y關鍵路徑做到這一點? – Msencenb

+0

對我來說,爲動畫設置一個鍵並不能代替隱式動畫,所以我不得不使用[這個答案](https://stackoverflow.com/a/2244734/865175)。 –

1

如果要讓動畫從結束位置開始,請將fromValue屬性設置爲CALayer的當前旋轉。

獲得該值是棘手的,但這SO後告訴您如何:https://stackoverflow.com/a/6706604/1072846

+0

我認爲這比另一個建議使用[animationDidStart:]的答案更合適,這是海報想要的東西 –