Pages

2011年11月13日日曜日

CoreAnimation CATransaction

CoreAnimationで、CATransactionを使う方法はシンプルで手軽なんで結構楽しめますよね。

もう識者の方にとっては当たり前で知ってることだとは思いますが、自分なりに簡単な実験を行ってみたので、ここに書き留めておきます。

とりあえず、100x100の青背景のCALayerを作ってアニメーションさせます。
アニメーションの開始はviewDidAppearとします。

まずは、5秒かけてゆっくり左上から右下にレイヤーを移動させながら、最初の1秒間でレイヤーの透明度を変更するという二つのアニメーションの組み合わせのパターン。
これは、CATransactionをネストすることで可能です。

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];

  [CATransaction begin];
  [CATransaction setAnimationDuration:5.0];
  animLayer.frame = CGRectMake(200.0, 340.0, 100.0, 100.0);
  [CATransaction begin];
  [CATransaction setAnimationDuration:1.0];
  animLayer.opacity = 0.3;
  [CATransaction commit];
  [CATransaction commit];
}


これをiPhoneシミュレータで実行させたらこうなります。


では、この透明度を変更するのがアニメーションの開始から3秒後に始めたい。こんな場合はどうするのってことで、以下のようなコードを書いてみました。タイマーを使用します。

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];

  [CATransaction begin];
  [CATransaction setAnimationDuration:5.0];
  animLayer.frame = CGRectMake(200.0, 340.0, 100.0, 100.0);
  [CATransaction commit];
  //
  [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:NO];
}

- (void)onTimer:(NSTimer*)timer {
  [CATransaction begin];
  [CATransaction setAnimationDuration:1.0];
  animLayer.opacity = 0.3;
  [CATransaction commit];
}




CATransactionはあとから実行しても追加して複数のアニメーションを組み合わせて実行くれるみたいですね。
では、こんなことしてみたらどうでしょうか?

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];

  [CATransaction begin];
  [CATransaction setAnimationDuration:5.0];
  animLayer.frame = CGRectMake(200.0, 340.0, 100.0, 100.0);
  [CATransaction commit];
  //
  [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:NO];
}

- (void)onTimer:(NSTimer*)timer {
  [CATransaction begin];
  [CATransaction setAnimationDuration:1.0];
  animLayer.frame = CGRectMake(20.0, 20.0, 100.0, 100.0);
  [CATransaction commit];
}



まぁ当然そうなりますよね。
CABasicAnimationでいうところのanimationWithKeyPathのkeyPathが同じものを重ねて追加すると上書きというか前のものが取り消されて後から追加したアニメーションが実行されます。

で、途中でアニメーションを中止させるには以下のようにすれば可能です。

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];

  [CATransaction begin];
  [CATransaction setAnimationDuration:5.0];
  animLayer.frame = CGRectMake(200.0, 340.0, 100.0, 100.0);
  [CATransaction commit];
  //
  [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:NO];
}

- (void)onTimer:(NSTimer*)timer {
  [animLayer removeAllAnimations];
}


0 コメント:

コメントを投稿