iOS動畫進階(九)圖層時間

圖層時間

時間和空間最大的區別在於,時間不能被複用 -- 弗斯特梅里克

在上面兩章中,我們探討了可以用CAAnimation和它的子類實現的多種圖層動畫。動畫的發生是需要持續一段時間的,所以計時對整個概念來說至關重要。在這一章中,我們來看看CAMediaTiming,看看Core Animation是如何跟蹤時間的。

CAMediaTiming協議

CAMediaTiming協議定義了在一段動畫內用來控制逝去時間的屬性的集合,CALayerCAAnimation都實現了這個協議,所以時間可以被任意基於一個圖層或者一段動畫的類控制。

持續和重複

我們在第八章“顯式動畫”中簡單提到過durationCAMediaTiming的屬性之一),duration是一個CFTimeInterval的類型(類似於NSTimeInterval的一種雙精度浮點類型),對將要進行的動畫的一次迭代指定了時間。

這裏的一次迭代是什麼意思呢?CAMediaTiming另外還有一個屬性叫做repeatCount,代表動畫重複的迭代次數。如果duration是2,repeatCount設爲3.5(三個半迭代),那麼完整的動畫時長將是7秒。

durationrepeatCount默認都是0。但這不意味着動畫時長爲0秒,或者0次,這裏的0僅僅代表了“默認”,也就是0.25秒和1次,你可以用一個簡單的測試來嘗試爲這兩個屬性賦多個值,如清單9.1,圖9.1展示了程序的結果。

清單9.1 測試durationrepeatCount

@interface ViewController ()

@property (nonatomic, weak) IBOutlet UIView *containerView;
@property (nonatomic, weak) IBOutlet UITextField *durationField;
@property (nonatomic, weak) IBOutlet UITextField *repeatField;
@property (nonatomic, weak) IBOutlet UIButton *startButton;
@property (nonatomic, strong) CALayer *shipLayer;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //add the ship
    self.shipLayer = [CALayer layer];
    self.shipLayer.frame = CGRectMake(0, 0, 128, 128);
    self.shipLayer.position = CGPointMake(150, 150);
    self.shipLayer.contents = (__bridge id)[UIImage imageNamed: @"Ship.png"].CGImage;
    [self.containerView.layer addSublayer:self.shipLayer];
}

- (void)setControlsEnabled:(BOOL)enabled
{
    for (UIControl *control in @[self.durationField, self.repeatField, self.startButton]) {
        control.enabled = enabled;
        control.alpha = enabled? 1.0f: 0.25f;
    }
}

- (IBAction)hideKeyboard
{
    [self.durationField resignFirstResponder];
    [self.repeatField resignFirstResponder];
}

- (IBAction)start
{
    CFTimeInterval duration = [self.durationField.text doubleValue];
    float repeatCount = [self.repeatField.text floatValue];
    //animate the ship rotation
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.rotation";
    animation.duration = duration;
    animation.repeatCount = repeatCount;
    animation.byValue = @(M_PI * 2);
    animation.delegate = self;
    [self.shipLayer addAnimation:animation forKey:@"rotateAnimation"];
    //disable controls
    [self setControlsEnabled:NO];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //reenable controls
    [self setControlsEnabled:YES];
}

@end

圖9.1

圖9.1 演示durationrepeatCount的測試程序

創建重複動畫的另一種方式是使用repeatDuration屬性,它讓動畫重複一個指定的時間,而不是指定次數。你甚至設置一個叫做autoreverses的屬性(BOOL類型)在每次間隔交替循環過程中自動回放。這對於播放一段連續非循環的動畫很有用,例如打開一扇門,然後關上它(圖9.2)。

圖9.2

圖9.2 擺動門的動畫

對門進行擺動的代碼見清單9.2。我們用了autoreverses來使門在打開後自動關閉,在這裏我們把repeatDuration設置爲INFINITY,於是動畫無限循環播放,設置repeatCountINFINITY也有同樣的效果。注意repeatCountrepeatDuration可能會相互衝突,所以你只要對其中一個指定非零值。對兩個屬性都設置非0值的行爲沒有被定義。

清單9.2 使用autoreverses屬性實現門的搖擺

@interface ViewController ()

@property (nonatomic, weak) UIView *containerView;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //add the door
    CALayer *doorLayer = [CALayer layer];
    doorLayer.frame = CGRectMake(0, 0, 128, 256);
    doorLayer.position = CGPointMake(150 - 64, 150);
    doorLayer.anchorPoint = CGPointMake(0, 0.5);
    doorLayer.contents = (__bridge id)[UIImage imageNamed: @"Door.png"].CGImage;
    [self.containerView.layer addSublayer:doorLayer];
    //apply perspective transform
    CATransform3D perspective = CATransform3DIdentity;
    perspective.m34 = -1.0 / 500.0;
    self.containerView.layer.sublayerTransform = perspective;
    //apply swinging animation
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.rotation.y";
    animation.toValue = @(-M_PI_2);
    animation.duration = 2.0;
    animation.repeatDuration = INFINITY;
    animation.autoreverses = YES;
    [doorLayer addAnimation:animation forKey:nil];
}

@end

相對時間

每次討論到Core Animation,時間都是相對的,每個動畫都有它自己描述的時間,可以獨立地加速,延時或者偏移。

beginTime指定了動畫開始之前的的延遲時間。這裏的延遲從動畫添加到可見圖層的那一刻開始測量,默認是0(就是說動畫會立刻執行)。

speed是一個時間的倍數,默認1.0,減少它會減慢圖層/動畫的時間,增加它會加快速度。如果2.0的速度,那麼對於一個duration爲1的動畫,實際上在0.5秒的時候就已經完成了。

timeOffsetbeginTime類似,但是和增加beginTime導致的延遲動畫不同,增加timeOffset只是讓動畫快進到某一點,例如,對於一個持續1秒的動畫來說,設置timeOffset爲0.5意味着動畫將從一半的地方開始。

beginTime不同的是,timeOffset並不受speed的影響。所以如果你把speed設爲2.0,把timeOffset設置爲0.5,那麼你的動畫將從動畫最後結束的地方開始,因爲1秒的動畫實際上被縮短到了0.5秒。然而即使使用了timeOffset讓動畫從結束的地方開始,它仍然播放了一個完整的時長,這個動畫僅僅是循環了一圈,然後從頭開始播放。

可以用清單9.3的測試程序驗證一下,設置speedtimeOffset滑塊到隨意的值,然後點擊播放來觀察效果(見圖9.3)

清單9.3 測試timeOffsetspeed屬性

@interface ViewController ()

@property (nonatomic, weak) IBOutlet UIView *containerView;
@property (nonatomic, weak) IBOutlet UILabel *speedLabel;
@property (nonatomic, weak) IBOutlet UILabel *timeOffsetLabel;
@property (nonatomic, weak) IBOutlet UISlider *speedSlider;
@property (nonatomic, weak) IBOutlet UISlider *timeOffsetSlider;
@property (nonatomic, strong) UIBezierPath *bezierPath;
@property (nonatomic, strong) CALayer *shipLayer;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //create a path
    self.bezierPath = [[UIBezierPath alloc] init];
    [self.bezierPath moveToPoint:CGPointMake(0, 150)];
    [self.bezierPath addCurveToPoint:CGPointMake(300, 150) controlPoint1:CGPointMake(75, 0) controlPoint2:CGPointMake(225, 300)];
    //draw the path using a CAShapeLayer
    CAShapeLayer *pathLayer = [CAShapeLayer layer];
    pathLayer.path = self.bezierPath.CGPath;
    pathLayer.fillColor = [UIColor clearColor].CGColor;
    pathLayer.strokeColor = [UIColor redColor].CGColor;
    pathLayer.lineWidth = 3.0f;
    [self.containerView.layer addSublayer:pathLayer];
    //add the ship
    self.shipLayer = [CALayer layer];
    self.shipLayer.frame = CGRectMake(0, 0, 64, 64);
    self.shipLayer.position = CGPointMake(0, 150);
    self.shipLayer.contents = (__bridge id)[UIImage imageNamed: @"Ship.png"].CGImage;
    [self.containerView.layer addSublayer:self.shipLayer];
    //set initial values
    [self updateSliders];
}

- (IBAction)updateSliders
{
    CFTimeInterval timeOffset = self.timeOffsetSlider.value;
    self.timeOffsetLabel.text = [NSString stringWithFormat:@"%0.2f", timeOffset];
    float speed = self.speedSlider.value;
    self.speedLabel.text = [NSString stringWithFormat:@"%0.2f", speed];
}

- (IBAction)play
{
    //create the keyframe animation
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"position";
    animation.timeOffset = self.timeOffsetSlider.value;
    animation.speed = self.speedSlider.value;
    animation.duration = 1.0;
    animation.path = self.bezierPath.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    animation.removedOnCompletion = NO;
    [self.shipLayer addAnimation:animation forKey:@"slide"];
}

@end

圖9.3

圖9.3 測試時間偏移和速度的簡單的應用程序

fillMode

對於beginTime非0的一段動畫來說,會出現一個當動畫添加到圖層上但什麼也沒發生的狀態。類似的,removeOnCompletion被設置爲NO的動畫將會在動畫結束的時候仍然保持之前的狀態。這就產生了一個問題,當動畫開始之前和動畫結束之後,被設置動畫的屬性將會是什麼值呢?

一種可能是屬性和動畫沒被添加之前保持一致,也就是在模型圖層定義的值(見第七章“隱式動畫”,模型圖層和呈現圖層的解釋)。

另一種可能是保持動畫開始之前那一幀,或者動畫結束之後的那一幀。這就是所謂的填充,因爲動畫開始和結束的值用來填充開始之前和結束之後的時間。

這種行爲就交給開發者了,它可以被CAMediaTimingfillMode來控制。fillMode是一個NSString類型,可以接受如下四種常量:

kCAFillModeForwards 
kCAFillModeBackwards 
kCAFillModeBoth 
kCAFillModeRemoved

默認是kCAFillModeRemoved,當動畫不再播放的時候就顯示圖層模型指定的值剩下的三種類型向前,向後或者即向前又向後去填充動畫狀態,使得動畫在開始前或者結束後仍然保持開始和結束那一刻的值。

這就對避免在動畫結束的時候急速返回提供另一種方案(見第八章)。但是記住了,當用它來解決這個問題的時候,需要把removeOnCompletion設置爲NO,另外需要給動畫添加一個非空的鍵,於是可以在不需要動畫的時候把它從圖層上移除。

層級關係時間

在第三章“圖層幾何學”中,你已經瞭解到每個圖層是如何相對在圖層樹中的父圖層定義它的座標系的。動畫時間和它類似,每個動畫和圖層在時間上都有它自己的層級概念,相對於它的父親來測量。對圖層調整時間將會影響到它本身和子圖層的動畫,但不會影響到父圖層。另一個相似點是所有的動畫都被按照層級組合(使用CAAnimationGroup實例)。

CALayer或者CAGroupAnimation調整durationrepeatCount/repeatDuration屬性並不會影響到子動畫。但是beginTimetimeOffsetspeed屬性將會影響到子動畫。然而在層級關係中,beginTime指定了父圖層開始動畫(或者組合關係中的父動畫)和對象將要開始自己動畫之間的偏移。類似的,調整CALayerCAGroupAnimationspeed屬性將會對動畫以及子動畫速度應用一個縮放的因子。

全局時間和本地時間

CoreAnimation有一個全局時間的概念,也就是所謂的馬赫時間(“馬赫”實際上是iOS和Mac OS系統內核的命名)。馬赫時間在設備上所有進程都是全局的--但是在不同設備上並不是全局的--不過這已經足夠對動畫的參考點提供便利了,你可以使用CACurrentMediaTime函數來訪問馬赫時間:

CFTimeInterval time = CACurrentMediaTime();

這個函數返回的值其實無關緊要(它返回了設備自從上次啓動後的秒數,並不是你所關心的),它真實的作用在於對動畫的時間測量提供了一個相對值。注意當設備休眠的時候馬赫時間會暫停,也就是所有的CAAnimations(基於馬赫時間)同樣也會暫停。

因此馬赫時間對長時間測量並不有用。比如用CACurrentMediaTime去更新一個實時鬧鐘並不明智。(可以用[NSDate date]代替,就像第三章例子所示)。

每個CALayerCAAnimation實例都有自己本地時間的概念,是根據父圖層/動畫層級關係中的beginTimetimeOffsetspeed屬性計算。就和轉換不同圖層之間座標關係一樣,CALayer同樣也提供了方法來轉換不同圖層之間的本地時間。如下:

- (CFTimeInterval)convertTime:(CFTimeInterval)t fromLayer:(CALayer *)l; 
- (CFTimeInterval)convertTime:(CFTimeInterval)t toLayer:(CALayer *)l;

當用來同步不同圖層之間有不同的speedtimeOffsetbeginTime的動畫,這些方法會很有用。

暫停,倒回和快進

設置動畫的speed屬性爲0可以暫停動畫,但在動畫被添加到圖層之後不太可能再修改它了,所以不能對正在進行的動畫使用這個屬性。給圖層添加一個CAAnimation實際上是給動畫對象做了一個不可改變的拷貝,所以對原始動畫對象屬性的改變對真實的動畫並沒有作用。相反,直接用-animationForKey:來檢索圖層正在進行的動畫可以返回正確的動畫對象,但是修改它的屬性將會拋出異常。

如果移除圖層正在進行的動畫,圖層將會急速返回動畫之前的狀態。但如果在動畫移除之前拷貝呈現圖層到模型圖層,動畫將會看起來暫停在那裏。但是不好的地方在於之後就不能再恢復動畫了。

一個簡單的方法是可以利用CAMediaTiming來暫停圖層本身。如果把圖層的speed設置成0,它會暫停任何添加到圖層上的動畫。類似的,設置speed大於1.0將會快進,設置成一個負值將會倒回動畫。

通過增加主窗口圖層的speed,可以暫停整個應用程序的動畫。這對UI自動化提供了好處,我們可以加速所有的視圖動畫來進行自動化測試(注意對於在主窗口之外的視圖並不會被影響,比如UIAlertview)。可以在app delegate設置如下進行驗證:

self.window.layer.speed = 100;

你也可以通過這種方式來減速,但其實也可以在模擬器通過切換慢速動畫來實現。

手動動畫

timeOffset一個很有用的功能在於你可以它可以讓你手動控制動畫進程,通過設置speed爲0,可以禁用動畫的自動播放,然後來使用timeOffset來來回顯示動畫序列。這可以使得運用手勢來手動控制動畫變得很簡單。

舉個簡單的例子:還是之前關門的動畫,修改代碼來用手勢控制動畫。我們給視圖添加一個UIPanGestureRecognizer,然後用timeOffset左右搖晃。

因爲在動畫添加到圖層之後不能再做修改了,我們來通過調整layertimeOffset達到同樣的效果(清單9.4)。

清單9.4 通過觸摸手勢手動控制動畫

@interface ViewController ()

@property (nonatomic, weak) UIView *containerView;
@property (nonatomic, strong) CALayer *doorLayer;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //add the door
    self.doorLayer = [CALayer layer];
    self.doorLayer.frame = CGRectMake(0, 0, 128, 256);
    self.doorLayer.position = CGPointMake(150 - 64, 150);
    self.doorLayer.anchorPoint = CGPointMake(0, 0.5);
    self.doorLayer.contents = (__bridge id)[UIImage imageNamed:@"Door.png"].CGImage;
    [self.containerView.layer addSublayer:self.doorLayer];
    //apply perspective transform
    CATransform3D perspective = CATransform3DIdentity;
    perspective.m34 = -1.0 / 500.0;
    self.containerView.layer.sublayerTransform = perspective;
    //add pan gesture recognizer to handle swipes
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] init];
    [pan addTarget:self action:@selector(pan:)];
    [self.view addGestureRecognizer:pan];
    //pause all layer animations
    self.doorLayer.speed = 0.0;
    //apply swinging animation (which won't play because layer is paused)
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.rotation.y";
    animation.toValue = @(-M_PI_2);
    animation.duration = 1.0;
    [self.doorLayer addAnimation:animation forKey:nil];
}

- (void)pan:(UIPanGestureRecognizer *)pan
{
    //get horizontal component of pan gesture
    CGFloat x = [pan translationInView:self.view].x;
    //convert from points to animation duration //using a reasonable scale factor
    x /= 200.0f;
    //update timeOffset and clamp result
    CFTimeInterval timeOffset = self.doorLayer.timeOffset;
    timeOffset = MIN(0.999, MAX(0.0, timeOffset - x));
    self.doorLayer.timeOffset = timeOffset;
    //reset pan gesture
    [pan setTranslation:CGPointZero inView:self.view];
}

@end

這其實是個小詭計,也許相對於設置個動畫然後每次顯示一幀而言,用移動手勢來直接設置門的transform會更簡單。

在這個例子中的確是這樣,但是對於比如說關鍵這這樣更加複雜的情況,或者有多個圖層的動畫組,相對於實時計算每個圖層的屬性而言,這就顯得方便的多了。

總結

在這一章,我們瞭解了CAMediaTiming協議,以及Core Animation用來操作時間控制動畫的機制。在下一章,我們將要接觸緩衝,另一個用來使動畫更加真實的操作時間的技術。

發佈了13 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章