CABasicAnimation使ってUIViewを360°回転させる方法のメモ
(iOS5 で試してます)
くるくる回すアニメーションはCABasicAnimationで実現可能
z軸周りで回転させる場合、次のパスを指定する。
transform.rotation.z
→ [CABasicAnimation animationWithKeyPath:@”transform.rotation.z”];
CABasicAnimationのデフォルト設定だと、
アニメーション終了後に回転した位置が元に戻ってしまう。
戻らないようにするためには、次の変更を行う。
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
サンプルコード
(ViewController.m に書いて試してます。)
– (void)viewDidLoad
{
[superviewDidLoad];
// 真ん中に四角を表示
UIView *turnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
turnView.backgroundColor = [UIColorredColor];
turnView.center = self.view.center;
[self.view addSubview:turnView];
// アニメーション
double rotation = M_PI * 0.3;
int repeat = 11;
double duration = 0.3;
CABasicAnimation* animation;
animation = [CABasicAnimation animationWithKeyPath:@”transform.rotation.z”];
animation.toValue = [NSNumber numberWithFloat: rotation];
animation.duration = duration;
animation.repeatCount = repeat;
// toValue を累計に : NOにするとカクカクするだけで回らない。
animation.cumulative = YES;
// アニメ終了後の回転角を保持する場合、
// fillMode, removeOnCompletionの設定
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
[turnView.layer addAnimation:animation forKey:@”rotationAnimation”];
}