iOS之核心動畫

這是我的第一篇簡書文章,希望大家多多關注

關于核心動畫的內容網上有很多,但是都不全或者沒有demo。我參考了下結合自己理解并寫了demo,如果覺得寫的不錯,請點個贊。

附demo地址DEMO

基本概念

1、核心動畫類的層次結構

Core Animation classes and protocol

CAAnimation是所有動畫對象的父類,實現CAMediaTiming協議,負責控制動畫的時間、速度和時間曲線等等,是一個抽象類,不能直接使用。
  CAPropertyAnimation :是CAAnimation的子類,它支持動畫地顯示圖層的keyPath,一般不直接使用。
  iOS9.0之后新增CASpringAnimation類,它實現彈簧效果的動畫,是CABasicAnimation的子類。

綜上,核心動畫類中可以直接使用的類有:

CABasicAnimation
  CAKeyframeAnimation
  CATransition
  CAAnimationGroup
  CASpringAnimation

2、什么是核心動畫

Core Animation(核心動畫)是一組功能強大、效果華麗的動畫API,無論在iOS系統或者在你開發的App中,都有大量應用。

相比UIView動畫,它可以實現更復雜的動畫效果。

核心動畫作用在CALayer(Core animation layer)上,CALayer從概念上類似UIView,我們可以將UIView看成是一種特殊的CALayer(可以響應事件)。
  實際上,每一個view都有其對應的layer,這個layer是root layer:

@property(nonatomic,readonly,strong)                 CALayer  *layer;

給view加上動畫,本質上是對其layer進行操作,layer包含了各種支持動畫的屬性,動畫則包含了屬性變化的值、變化的速度、變化的時間等等,兩者結合產生動畫的過程。

核心動畫和UIView動畫的對比:UIView動畫可以看成是對核心動畫的封裝,和UIView動畫不同的是,通過核心動畫改變layer的狀態(比如position),動畫執行完畢后實際上是沒有改變的(表面上看起來已改變)。

CALayer的基本屬性

寬度和高度:
@property CGRect bounds;

位置(默認指中點,具體由anchorPoint決定):
@property CGPoint position;

錨點(x,y的范圍都是0-1),決定了position的含義:
@property CGPoint anchorPoint;

背景顏色(CGColorRef類型):
@property CGColorRef backgroundColor;

形變屬性:
@property CATransform3D transform;

position和anchorPoint的作用

@property CGPoint position;:

用來設置CALayer在父層中的位置
以父層的左上角為原點(0, 0)

@property CGPoint anchorPoint;:

稱為“定位點”、“錨點”,
決定著CALayer身上的哪個點會在position屬性所指的位置。
以自己的左上角為原點(0, 0),
它的x、y取值范圍都是0~1,默認值為中心點(0.5, 0.5)

anchorPoint和position的關系舉例:

假如錨點anchorPoint為默認值即中點(0.5,0.5),而該層的position設置為(0,0)即為父層的左上點,那么該層在父層中只會看到四分之一的部分。

anchorPoint

UIView和CALayer的選擇

通過CALayer,就能做出跟UIImageView一樣的界面效果。

既然CALayer和UIView都能實現相同的顯示效果,那究竟該選擇誰好呢?

其實,對比CALayer,UIView多了一個事件處理的功能。也就是說,CALayer不能處理用戶的觸摸事件,而UIView可以
所以,如果顯示出來的東西需要跟用戶進行交互的話,用UIView;如果不需要跟用戶進行交互,用UIView或者CALayer都可以。當然,CALayer的性能會高一些,因為它少了事件處理的功能,更加輕量級。

為什么CALayer不能直接使用UIColor,UIImage?

layer.backgroundColor = [UIColor redColor].CGColor;

首先,CALayer是定義在QuartzCore框架中的,CGImageRef、CGColorRef兩種數據類型是定義在CoreGraphics框架中的
,而UIColor和UIImage是定義在UIKit框架中的。

其次,QuartzCore框架和CoreGraphics框架是可以跨平臺使用的,在iOS和Mac OS X上都能使用
但是UIKit只能在iOS中使用。

所以,為了保證可移植性,QuartzCore不能使用UIImage、UIColor,只能使用CGImageRef、CGColorRef。

總體來說核心動畫的優點有:

1)性能強大,使用硬件加速,可以同時向多個圖層添加不同的動畫效果
2)接口易用,只需要少量的代碼就可以實現復雜的動畫效果。
3)運行在后臺線程中,在動畫過程中可以響應交互事件(UIView動畫默認動畫過程中不響應交互事件)。

3、基本屬性說明:

屬性 說明

repeatCount   重復次數,無限循環可以設置HUGE_VALF或者MAXFLOAT
repeatDuration   重復時間
removedOnCompletion 默認為YES,代表動畫執行完畢后就從圖層上移除,圖形會恢復到動畫執行前的狀態。如果想讓圖層保持顯示動畫執行后的狀態,那就設置為NO,不過還要設置fillMode為       kCAFillModeForwards
fillMode    決定當前對象在非active時間段的行為。比如動畫開始之前或者動畫結束之
beginTime   可以用來設置動畫延遲執行時間,若想延遲2s,就設置為CACurrentMediaTime()+2,CACurrentMediaTime()為圖層的當前時間
timingFunction  速度控制函數,控制動畫運行的節奏
delegate    動畫代理```
####fillMode屬性的設置:
    kCAFillModeRemoved 這個是默認值,也就是說當動畫開始前和動畫結束后,動畫對layer都沒有影響,動畫結束后,layer會恢復到之前的狀態
    kCAFillModeForwards 當動畫結束后,layer會一直保持著動畫最后的狀態
    kCAFillModeBackwards 在動畫開始前,只需要將動畫加入了一個layer,layer便立即進入動畫的初始狀態并等待動畫開始。
    kCAFillModeBoth 這個其實就是上面兩個的合成.動畫加入后開始之前,layer便處于動畫初始狀態,動畫結束后layer保持動畫最后的狀態
####速度控制函數(CAMediaTimingFunction):
```kCAMediaTimingFunctionLinear(線性):勻速,給你一個相對靜態的感覺
kCAMediaTimingFunctionEaseIn(漸進):動畫緩慢進入,然后加速離開
kCAMediaTimingFunctionEaseOut(漸出):動畫全速進入,然后減速的到達目的地
kCAMediaTimingFunctionEaseInEaseOut(漸進漸出):動畫緩慢的進入,中間加速,然后減速的到達目的地。這個是默認的動畫行為。```
####CALayer上動畫的暫停和恢復

-(void)pauseLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];

// 讓CALayer的時間停止走動
  layer.speed = 0.0;
// 讓CALayer的時間停留在pausedTime這個時刻
layer.timeOffset = pausedTime;

}

-(void)resumeLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = layer.timeOffset;
// 1. 讓CALayer的時間繼續行走
layer.speed = 1.0;
// 2. 取消上次記錄的停留時刻
layer.timeOffset = 0.0;
// 3. 取消上次設置的時間
layer.beginTime = 0.0;
// 4. 計算暫停的時間(這里也可以用CACurrentMediaTime()-pausedTime)
CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
// 5. 設置相對于父坐標系的開始時間(往后退timeSincePause)
layer.beginTime = timeSincePause;
}

####動畫的添加和移除
    - (void)addAnimation:(CAAnimation *)anim forKey:(nullable NSString *)key;
    - (void)removeAnimationForKey:(NSString *)key;
    - (void)removeAllAnimations;
####核心動畫類的常用屬性
  keyPath:可以指定keyPath為CALayer的屬性值,并對它的值進行修改,以達到對應的動畫效果,需要注意的是部分屬性值是不支持動畫效果的。
  以下是具有動畫效果的keyPath:
 ```//CATransform3D Key Paths : (example)transform.rotation.z
      //rotation.x
     //rotation.y
     //rotation.z
     //rotation 旋轉
     //scale.x
     //scale.y
     //scale.z
     //scale 縮放
     //translation.x
     //translation.y
     //translation.z
         //translation 平移
     //CGPoint Key Paths : (example)position.x
     //x
     //y
     //CGRect Key Paths : (example)bounds.size.width
     //origin.x
     //origin.y
     //origin
     //size.width
     //size.height
     //size
     //opacity
     //backgroundColor
     //cornerRadius 
     //borderWidth
     //contents 
     //Shadow Key Path:
     //shadowColor 
     //shadowOffset 
     //shadowOpacity 
     //shadowRadius```
#CABasicAnimation
  CABasicAnimation可以設定keyPath的起點,終點的值,動畫會沿著設定點進行移動,CABasicAnimation可以看成是只有兩個關鍵點的特殊的CAKeyFrameAnimation。
  • (void)position {
    CABasicAnimation * ani = [CABasicAnimation animationWithKeyPath:@"position"];
    ani.toValue = [NSValue valueWithCGPoint:self.centerShow.center];
    ani.removedOnCompletion = NO;
    ani.fillMode = kCAFillModeForwards;
    ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.cartCenter.layer addAnimation:ani forKey:@"PostionAni"];
    }
動畫效果:

![position.gif](http://upload-images.jianshu.io/upload_images/4857684-817f59b2d5816834.gif?imageMogr2/auto-orient/strip)
下面是部分keyPath對應的動畫效果(圖片名為其對應的keyPath):

![position.x.gif](http://upload-images.jianshu.io/upload_images/4857684-d8a078799ec71f09.gif?imageMogr2/auto-orient/strip)


![position.y.gif](http://upload-images.jianshu.io/upload_images/4857684-c12982d76d893d69.gif?imageMogr2/auto-orient/strip)
![transform.rotation.x.gif](http://upload-images.jianshu.io/upload_images/4857684-c0001648027e29e4.gif?imageMogr2/auto-orient/strip)


![transform.rotation.y.gif](http://upload-images.jianshu.io/upload_images/4857684-559eea05f8dbef55.gif?imageMogr2/auto-orient/strip)
![transform.rotation.z.gif](http://upload-images.jianshu.io/upload_images/4857684-170bdc7ff71dffe5.gif?imageMogr2/auto-orient/strip)
![transform.scale.gif](http://upload-images.jianshu.io/upload_images/4857684-d5b60ba6b101f4bd.gif?imageMogr2/auto-orient/strip)
![transform.translation.x.gif](http://upload-images.jianshu.io/upload_images/4857684-2c18a3f63eecaffa.gif?imageMogr2/auto-orient/strip)
![bounds.size.gif](http://upload-images.jianshu.io/upload_images/4857684-b632ad8e58240d70.gif?imageMogr2/auto-orient/strip)
![opacity.gif](http://upload-images.jianshu.io/upload_images/4857684-e345539725a12abc.gif?imageMogr2/auto-orient/strip)
![backgroundColor.gif](http://upload-images.jianshu.io/upload_images/4857684-bfa5fff119f39da9.gif?imageMogr2/auto-orient/strip)
![cornerRadius.gif](http://upload-images.jianshu.io/upload_images/4857684-bfef2561219ea37a.gif?imageMogr2/auto-orient/strip)
![borderWidth.gif](http://upload-images.jianshu.io/upload_images/4857684-9f8984ac51a0b563.gif?imageMogr2/auto-orient/strip)
![contents.gif](http://upload-images.jianshu.io/upload_images/4857684-7f9d98fefbb22e57.gif?imageMogr2/auto-orient/strip)
![shadowColor.gif](http://upload-images.jianshu.io/upload_images/4857684-85f9039fe7a7e14c.gif?imageMogr2/auto-orient/strip)
![shadowOffset.gif](http://upload-images.jianshu.io/upload_images/4857684-f7f53c800d3aff02.gif?imageMogr2/auto-orient/strip)
![shadowOpacity.gif](http://upload-images.jianshu.io/upload_images/4857684-e74a69c19e86fd92.gif?imageMogr2/auto-orient/strip)
![shadowRadius.gif](http://upload-images.jianshu.io/upload_images/4857684-2fae023cfafce61e.gif?imageMogr2/auto-orient/strip)
#CAKeyframeAnimation
  values:關鍵幀數組對象,里面每一個元素即為一個關鍵幀,動畫會在對應的時間段內,依次執行數組中每一個關鍵幀的動畫。
  path:動畫路徑對象,可以指定一個路徑,在執行動畫時路徑會沿著路徑移動,Path在動畫中只會影響視圖的Position。
  keyTimes:設置關鍵幀對應的時間點,范圍:0-1。如果沒有設置該屬性,則每一幀的時間平分。
####設置values使其沿正方形運動
  • (void)valueKeyframeAni {
    CAKeyframeAnimation * ani = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    ani.duration = 4.0;
    ani.removedOnCompletion = NO;
    ani.fillMode = kCAFillModeForwards;
    ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    NSValue * value1 = [NSValue valueWithCGPoint:CGPointMake(150, 200)];
    NSValue *value2=[NSValue valueWithCGPoint:CGPointMake(250, 200)];
    NSValue *value3=[NSValue valueWithCGPoint:CGPointMake(250, 300)];
    NSValue *value4=[NSValue valueWithCGPoint:CGPointMake(150, 300)];
    NSValue *value5=[NSValue valueWithCGPoint:CGPointMake(150, 200)];
    ani.values = @[value1, value2, value3, value4, value5];
    [self.centerShow.layer addAnimation:ani forKey:@"PostionKeyframeValueAni"];
    }



![正方形軌跡.gif](http://upload-images.jianshu.io/upload_images/4857684-9d08214be8cc1d7a.gif?imageMogr2/auto-orient/strip)
####設置path使其繞圓圈運動

![圓形軌跡.gif](http://upload-images.jianshu.io/upload_images/4857684-bd3dc1239cb927d9.gif?imageMogr2/auto-orient/strip)
#CATransition
CATransition是CAAnimation的子類,用于做轉場動畫,能夠為層提供移出屏幕和移入屏幕的動畫效果。iOS比Mac OS X的轉場動畫效果少一點。

UINavigationController就是通過CATransition實現了將控制器的視圖推入屏幕的動畫效果。
####屬性說明:

####屬性  說明
    type    動畫過渡類型
    subtype 動畫過度方向
    startProgress   動畫起點(在整體動畫的百分比)
    endProgress 動畫終點(在整體動畫的百分比)


![過渡效果設置](http://upload-images.jianshu.io/upload_images/4857684-d1a80f6780a1efee.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
以漸變效果為例
  • (void)transitionAni {
    CATransition * ani = [CATransition animation];
    ani.type = kCATransitionFade;
    ani.subtype = kCATransitionFromLeft;
    ani.duration = 1.5;
    self.centerShow.image = [UIImage imageNamed:@"Raffle"];
    [self.centerShow.layer addAnimation:ani forKey:@"transitionAni"];
    }
圖片名稱對應其type類型



![kCATransitionFade.gif](http://upload-images.jianshu.io/upload_images/4857684-074c6ceda603c897.gif?imageMogr2/auto-orient/strip)
![kCATransitionMoveIn.gif](http://upload-images.jianshu.io/upload_images/4857684-22371a1a19616c5a.gif?imageMogr2/auto-orient/strip)
![kCATransitionPush.gif](http://upload-images.jianshu.io/upload_images/4857684-54fdf38643fcf3a6.gif?imageMogr2/auto-orient/strip)
![kCATransitionReveal.gif](http://upload-images.jianshu.io/upload_images/4857684-50f908e379034b30.gif?imageMogr2/auto-orient/strip)
![rippleEffect.gif](http://upload-images.jianshu.io/upload_images/4857684-9443b238aa3ae061.gif?imageMogr2/auto-orient/strip)
![pageCurl.gif](http://upload-images.jianshu.io/upload_images/4857684-ee452fa489042888.gif?imageMogr2/auto-orient/strip)
![suckEffect.gif](http://upload-images.jianshu.io/upload_images/4857684-b1592453ca9fb2b1.gif?imageMogr2/auto-orient/strip)
![cube.gif](http://upload-images.jianshu.io/upload_images/4857684-025abb1dcca535f8.gif?imageMogr2/auto-orient/strip)
#CASpringAnimation
CASpringAnimation是iOS9新加入動畫類型,是CABasicAnimation的子類,用于實現彈簧動畫。
####CASpringAnimation的重要屬性:
  mass:質量(影響彈簧的慣性,質量越大,彈簧慣性越大,運動的幅度越大)
  stiffness:彈性系數(彈性系數越大,彈簧的運動越快)
  damping:阻尼系數(阻尼系數越大,彈簧的停止越快)
  initialVelocity:初始速率(彈簧動畫的初始速度大小,彈簧運動的初始方向與初始速率的正負一致,若初始速率為0,表示忽略該屬性)
  settlingDuration:結算時間(根據動畫參數估算彈簧開始運動到停止的時間,動畫設置的時間最好根據此時間來設置)
####CASpringAnimation和UIView的SpringAnimation對比:
  1.CASpringAnimation 可以設置更多影響彈簧動畫效果的屬性,可以實現更復雜的彈簧動畫效果,且可以和其他動畫組合。
  2.UIView的SpringAnimation實際上就是通過CASpringAnimation來實現。

  以實現視圖的bounds變化的彈簧動畫效果為例:
  • (void)springAni {
    CASpringAnimation * ani = [CASpringAnimation animationWithKeyPath:@"bounds"];
    ani.mass = 10.0; //質量,影響圖層運動時的彈簧慣性,質量越大,彈簧拉伸和壓縮的幅度越大
    ani.stiffness = 5000; //剛度系數(勁度系數/彈性系數),剛度系數越大,形變產生的力就越大,運動越快
    ani.damping = 100.0;//阻尼系數,阻止彈簧伸縮的系數,阻尼系數越大,停止越快
    ani.initialVelocity = 5.f;//初始速率,動畫視圖的初始速度大小;速率為正數時,速度方向與運動方向一致,速率為負數時,速度方向與運動方向相反
    ani.duration = ani.settlingDuration;
    ani.toValue = [NSValue valueWithCGRect:self.centerShow.bounds];
    ani.removedOnCompletion = NO;
    ani.fillMode = kCAFillModeForwards;
    ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.cartCenter.layer addAnimation:ani forKey:@"boundsAni"];
    }



![彈簧動畫.gif](http://upload-images.jianshu.io/upload_images/4857684-eb08b32108b05536.gif?imageMogr2/auto-orient/strip)
#CAAnimationGroup
  使用Group可以將多個動畫合并一起加入到層中,Group中所有動畫并發執行,可以方便地實現需要多種類型動畫的場景。

  以實現視圖的position、bounds和opacity改變的組合動畫為例
  • (void)groupAni {
    CABasicAnimation * posAni = [CABasicAnimation animationWithKeyPath:@"position"];
    posAni.toValue = [NSValue valueWithCGPoint:self.centerShow.center];

    CABasicAnimation * opcAni = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opcAni.toValue = [NSNumber numberWithFloat:1.0];
    opcAni.toValue = [NSNumber numberWithFloat:0.7];

    CABasicAnimation * bodAni = [CABasicAnimation animationWithKeyPath:@"bounds"];
    bodAni.toValue = [NSValue valueWithCGRect:self.centerShow.bounds];

    CAAnimationGroup * groupAni = [CAAnimationGroup animation];
    groupAni.animations = @[posAni, opcAni, bodAni];
    groupAni.duration = 1.0;
    groupAni.fillMode = kCAFillModeForwards;
    groupAni.removedOnCompletion = NO;
    groupAni.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.cartCenter.layer addAnimation:groupAni forKey:@"groupAni"];
    }





![組合動畫.gif](http://upload-images.jianshu.io/upload_images/4857684-f4401a0acc157aca.gif?imageMogr2/auto-orient/strip)

#CATransaction

  最后講一下事務,在核心動畫里面存在事務(CATransaction)這樣一個概念,它負責協調多個動畫原子更新顯示操作。
  簡單來說事務是核心動畫里面的一個基本的單元,動畫的產生必然伴隨著layer的Animatable屬性的變化,而layer屬性的變化必須屬于某一個事務。
  因此,核心動畫依賴事務。

  事務的作用:保證一個或多個layer的一個或多個屬性變化同時進行
  事務分為隱式和顯式:
  1.隱式:沒有明顯調用事務的方法,由系統自動生成事務。比如直接設置一個layer的position屬性,則會在當前線程自動生成一個事務,并在下一個runLoop中自動commit事務。
  2.顯式:明顯調用事務的方法([CATransaction begin]和[CATransaction commit])。

  CA事務的可設置屬性(會覆蓋隱式動畫的設置):

    animationDuration:動畫時間
    animationTimingFunction:動畫時間曲線
    disableActions:是否關閉動畫
    completionBlock:動畫執行完畢的回調
  事務支持嵌套使用:當最外層的事務commit后動畫才會開始。

  使用實例:

    [CATransaction begin];
    [CATransaction setAnimationDuration:2.0];
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    //    [CATransaction setDisableActions:YES]; //設置為YES就關閉動畫
    self.subLayer.bounds = self.centerShow.layer.bounds;
    [CATransaction commit];
  注意:只有非root layer才有隱式動畫,如果你是直接設置`self.cartCenter.layer.bounds = self.centerShow.layer.bounds;`是不會有動畫效果的。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 在iOS中隨處都可以看到絢麗的動畫效果,實現這些動畫的過程并不復雜,今天將帶大家一窺ios動畫全貌。在這里你可以看...
    每天刷兩次牙閱讀 8,573評論 6 30
  • 核心動畫(Core Animation) Core Animation,中文翻譯為核心動畫,它是一組非常強大的動畫...
    李小南閱讀 804評論 2 15
  • CALayer與UIView的關系 在iOS中,你能看得見摸得著的東西基本上都是UIView。在創建UIView對...
    charlotte2018閱讀 574評論 0 4
  • 在iOS實際開發中常用的動畫無非是以下四種:UIView動畫,核心動畫,幀動畫,自定義轉場動畫。 1.UIView...
    請叫我周小帥閱讀 3,169評論 1 23
  • 在iOS中隨處都可以看到絢麗的動畫效果,實現這些動畫的過程并不復雜,今天將帶大家一窺iOS動畫全貌。在這里你可以看...
    F麥子閱讀 5,147評論 5 13