2014-01-21 35 views
0

我只是想知道這是否是用CABasicAnimation動畫CALayer的正確方法。對於UI對象和CALayers,CABasicAnimation練習是否有所不同?

在堆棧溢出我已經學會了如何通過運行一個CABasicAnimation之前設置一個新的位置,以動畫UI對象:

動畫UI目標實例

gameTypeControl.center = CGPointMake(gameTypeControl.center.x, -slidingUpValue/2); 
CABasicAnimation *removeGameTypeControl = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"]; 
[removeGameTypeControl setFromValue:[NSNumber numberWithFloat:slidingUpValue]]; 
[removeGameTypeControl setToValue:[NSNumber numberWithFloat:0]]; 
[removeGameTypeControl setDuration:1.0]; 
[removeGameTypeControl setTimingFunction:[CAMediaTimingFunction functionWithControlPoints:0.8 :-0.8 :1.0 :1.0]]; 
[[gameTypeControl layer] addAnimation:removeGameTypeControl forKey:@"removeGameTypeControl"]; 

現在我已經試過這個方法在CALayer上,但它似乎工作不同。對我來說,得到相同的結果。我已經將ToValue設置爲新的y位置,而不是像使用UI對象動畫一樣使用值0。

動畫一個CALayer的實例

serveBlock2.position = CGPointMake((screenBounds.size.height/4)*3, -screenBounds.size.width/2); 
CABasicAnimation *updateCurrentServe2 = [CABasicAnimation animationWithKeyPath:@"position.y"]; 
updateCurrentServe2.fromValue = [NSNumber numberWithFloat:slidingUpValue/2]; 
[updateCurrentServe2 setToValue:[NSNumber numberWithFloat:-screenBounds.size.width/2]]; 
[updateCurrentServe2 setDuration:1.0]; 
[serveBlock2 addAnimation:updateCurrentServe2 forKey:@"serveBlock2 updateCurrentServe2"]; 

這是正確的嗎?我做對了嗎?

+0

'serveBlock2'是一個CALayer。 '[gameTypeControl層]'是一個CALayer。這些例子是一樣的。 – matt

回答

0

問題是,如果serveBlock2不是視圖的直接底層,那麼在第二個示例的第一行中設置其position將啓動不同的動畫(隱式動畫)。防止這種情況的方法是關閉隱式動畫。因此,這個例子from my book

CompassLayer* c = (CompassLayer*)self.compass.layer; 
[CATransaction setDisableActions:YES]; // <=== this is important 
c.arrow.transform = CATransform3DRotate(c.arrow.transform, M_PI/4.0, 0, 0, 1); 
CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform"]; 
anim.duration = 0.8; 
[c.arrow addAnimation:anim forKey:nil]; 

這樣,我不必有fromValuetoValue!表示層和模型層自動識別舊值和新值。

+0

您好,請您詳細說明一下在上面的示例中,如何自動從表示層和模型層中知道舊值和新值?如果我理解正確:通過使用'setDisableAction:YES',我們可以防止'c'被隱式地動畫化,所以直到你調用'CABasicAnimation',變換纔會發生,我正確嗎?謝謝。 – Unheilig

+0

動畫發生在當前CATransaction結束之後。 – matt

+0

@Unheilig變換(或任何其他變化)現在發生。但是用戶沒有看到它,因爲表示層直到動畫開始纔開始移動,這是晚些時候。請參閱動畫運行時的[我的解釋](http://www.apeth.com/iOSBook/ch17.html#_drawing_animation_and_threading)以及它如何工作。 – matt

相關問題