Search code examples
iphoneobjective-cipadcore-animation

adding bounce effect to appearance of UIImageView


How can I add a bounce effect when I am about to show an UIImageView as a subview? Do I have to use CoreAnimation to do this? My only guess right now is to use CAKeyframeAnimation, please let me know if there's a better way. Here's my current code:

 CABasicAnimation * theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    theAnimation.delegate = self;
    theAnimation.duration = 1.0;
    theAnimation.fromValue = [NSNumber numberWithFloat:notif.center.y];
    theAnimation.toValue = [NSNumber numberWithFloat:notif.center.y-20];
    theAnimation.repeatCount = 3;

Solution

  • y-axis animation using CABasicAnimation:

    CGPoint origin = self.imageView.center;
    CGPoint target = CGPointMake(self.imageView.center.x, self.imageView.center.y+100);
    CABasicAnimation *bounce = [CABasicAnimation animationWithKeyPath:@"position.y"];
    bounce.duration = 0.5;
    bounce.fromValue = [NSNumber numberWithInt:origin.y];
    bounce.toValue = [NSNumber numberWithInt:target.y];
    bounce.repeatCount = 2;
    bounce.autoreverses = YES;
    [self.imageView.layer addAnimation:bounce forKey:@"position"];
    

    If you want to implement shrink and grow you have to add a CGAffineTransformMakeScale, eg:

    // grow
    CGAffineTransform transform = CGAffineTransformMakeScale(1.3, 1.3);
    imageView.transform = transform;