Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mimic UIAlertView Bounce?

Whats the best way to mimic the bouncing animation from the UIAlertView on the iPhone? Is there some built-in mechanism for this? The UIAlertView itself won't work for my needs.

I looked into animation curves but from what I can tell the only ones they provide are easeIn, easeOut, and linear.

like image 427
Mike Buss Avatar asked Jan 29 '10 05:01

Mike Buss


3 Answers

UIAlertView uses a more sophisticated animation:

  • scale to larger than 100%
  • scale to smaller than 100%
  • scale to 100%

Here's an implementation using a CAKeyFrameAnimation:

view.alpha = 0;
[UIView animateWithDuration:0.1 animations:^{view.alpha = 1.0;}];

CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
bounceAnimation.values = @[@0.01f, @1.1f, @0.8f, @1.0f];
bounceAnimation.keyTimes = @[@0.0f, @0.5f, @0.75f, @1.0f];
bounceAnimation.duration = 0.4;
[view.layer addAnimation:bounceAnimation forKey:@"bounce"];
like image 194
Ortwin Gentz Avatar answered Nov 12 '22 07:11

Ortwin Gentz


I investigated how animations are added to UIAlertView's layer by swizzling -[CALayer addAnimation:forKey:]. Here are the values I got for the scale transform animations it performs:

0.01f -> 1.10f -> 0.90f -> 1.00f

with durations

0.2s, 0.1s, 0.1s.

All the animations use an ease in/ease out timing function. Here is a CAKeyframeAnimation that encapsulates this logic:

CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
bounceAnimation.fillMode = kCAFillModeBoth;
bounceAnimation.removedOnCompletion = YES;
bounceAnimation.duration = 0.4;
bounceAnimation.values = @[
    [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 0.01f)],
    [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.1f)],
    [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 0.9f)],
    [NSValue valueWithCATransform3D:CATransform3DIdentity]];
bounceAnimation.keyTimes = @[@0.0f, @0.5f, @0.75f, @1.0f];
bounceAnimation.timingFunctions = @[
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

I believe UIAlertView also performs a simple opacity animation from 0.0f to 1.0f over the total duration of the transform animation (0.4).

like image 30
CIFilter Avatar answered Nov 12 '22 09:11

CIFilter


You can use 2 animations, one to pop up to very large, and the other one to rescale back to normal size.

(This is the approach use by UIAlertView internally.)

Alternatively, you can use the lower-level CAAnimation and use +[CAMediaTimingFunction functionWithControlPoints::::] to make your own curve.

like image 3
kennytm Avatar answered Nov 12 '22 07:11

kennytm