14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Objective-C] CAKeyframeAnimationでイージング

Posted at

iOS(Objective-C)には標準で色々アニメーションするようにできています。
簡単なアニメーションなら組み込みのものを組み合わせるだけである程度動きのあるものが作れますね。

ただ、やはり味のある演出をしようとするとどうしても独自のアニメーションを実装する必要が出てきます。
JavaScriptの場合はrequestAnimationFrameなどを使ってタイマーを回しつつ、独自で計算した結果をDOMに反映する、というのが一般的です。(というかそういう方法しかない)

ただ、低レベルAPIで動作を作るがゆえに、細かい制御は比較的簡単にできました。
巷にあるイージング関数とかをさくっと利用することもそれほどむずかしくありません。

Objective-Cでそれをやろうとしたときに、どうしたらいいのかなーと探していたら、CAKeyframeAnimationを使うことで、同様のことができるみたいです。

ということで、前置きが長くなりましたが、CAKeyframeAnimationを使って独自のイージング関数を利用するサンプルのメモです。

イージング関数を用意

まず最初に、なにがしかのイージングをする関数を用意します。
どういう関数を作るかというと、以下のように与えられた情報を元に、配列として先に計算結果を返す関数を作ります。

// 与えられた情報から、イージングの計算をする関数
double easing(double t, double b, double c, double d)
{
	return c * t / d + b;
}

// 与えられた情報から、イージングの結果の配列を返す関数
NSArray * anyEasing(double startValue, double endValue, double duration)
{
	NSMutableArray *values = [NSMutableArray arrayWithCapacity:duration);
	double t = 1 / duration;
	double distance = endValue - startValue;

	for (int i = 0; i <= duration; i++) {
		double currentTime = (t * i) * duration;
		double value = easing(currentTime, startValue, distance, duration);
		[values addObject:[NSNumber numberWithDouble:value]];
	}

	return values;
}

イージングを適用する

double duration = 5;

CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position.y"];
animation.values = anyEasing(0, 100, duration);
animation.duration = duration;
animation.removeOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;

[aView.layer addAnimation:animation forKey:nil];

上記の関数で生成したイージングの結果の配列をCAKeyframeAnimation.valuesに設定し、各種設定を行ったら、最後にレイヤーのaddAnimation:forKey:メソッドに生成したアニメーションを設定すれば完了です。

14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?