標籤:
想在CALayer中實現動畫很容易,初學者可能會把思想局限於UIView層面上,其實不放用CALayer會比你想象的簡單且思路清晰,上篇隨筆中講到了CALayer的一些屬性,如果說你改變一些屬性比如bounds,position你會發現它是會內建隱式動畫的,而且效果不錯,不過在這裡你不能自訂動畫事件並且讓一組動畫有效執行。如果想實現上述的效果就需要CABaseAnimation
//顯示動畫 CABasicAnimation * contentAnimation = [CABasicAnimation animationWithKeyPath:@"contents"]; contentAnimation.fromValue = self.imageLayer.contents; contentAnimation.toValue = (__bridge id)(image2.CGImage); contentAnimation.duration = 1.0f; //bounds動畫 CABasicAnimation * boundsAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"]; boundsAnimation.fromValue = [NSValue valueWithCGRect:self.imageLayer.bounds]; boundsAnimation.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 1, 1)]; boundsAnimation.duration = 1.0f; //組合動畫 CAAnimationGroup * grounp = [CAAnimationGroup animation]; grounp.animations = @[contentAnimation,boundsAnimation]; grounp.duration = 1.0f; //設定layer動畫結束之後的值 self.imageLayer.bounds = CGRectMake(0, 0, 1, 1); self.imageLayer.contents = (__bridge id)(image2.CGImage); [self.imageLayer addAnimation:grounp forKey:nil];
如上代碼實現的是一個組合動畫,包括圖片的變換和Layer bounds的改變,在建立animation 的時候要寫入你要改變的屬性名稱,這個一定不要寫錯,fromValue需要寫入屬性的初始狀態,toValue需要寫入屬性變化後的值,輸入值都為對象,最後動畫是不會真的改變layer的屬性值的,如果不作處理動畫執行完後會變回初始狀態,想保留原來狀態需再最後賦值。
ios晉級之路-動畫CABaseAnimation