病みつきエンジニアブログ

機械学習、Python、Scala、JavaScript、などなど

Core Animationでバウンド表現

バウンド表現は、簡単なものなら簡単にできます。どちらかと言うとバネ表現と言ったほうが適切かもしれませんが。

基本的なアニメーションの仕組みなどの説明は省きます。「Core Animation」でおググりください。
下記コードで再現できます。

    // _label is the layer i wanna bounce
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    CGPoint origin = _label.layer.position;
    animation.fromValue = [NSValue valueWithCGPoint:origin];
    animation.toValue = [NSValue valueWithCGPoint:CGPointMake(origin.x + 50, origin.y - 50)];
    animation.duration = 0.5;
    animation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.33 :1.77 :0.62 :0.78];
    [_label.layer addAnimation:animation forKey:@"move"];

最後から2行目、timingFunctionを設定するのが味噌です。
CSS3 のアニメーションのeasing 同様、kCAMediaTimingFunction*でease-in-outなど基本的なものは定義されてますが、
CSS3 のアニメーションのeasing 同様、cubic-bezierを使って自分で定義することもできます。

cubic-bezier.comを使うと、グラフィカルにイージングを設定できます。
付け加えると、CSS3のcubic-bezierと違い、ちょっと無茶ができます。というのはCSS3では各値は0〜1でなくてはならないようですが、CAMediaTimingFunctionの場合、同様の制限はありません。

先ほどのcubic-bezierはhttp://cubic-bezier.com/#.33,1.77,.62,.78です。
Have a nice curve!