Dasem Dasem - 10 months ago 56
iOS Question

Card flipping animation

How is this animation achieved? <- link

I am making a card game and would like to use a similar animation.

Currently I'm using this code with two images, front and back:
card, is a uiview with two UIImageView propertys

[UIView transitionWithView:card duration:0.65f
options:UIViewAnimationOptionTransitionFlipFromRight animations:^{
card.backImageView.image = card.frontImageView.image;
card.layer.shadowOpacity = 0.8;
} completion:^(BOOL finished){
card.layer.shadowOpacity = 0.0;

Answer Source

In order to create a basic card flipping animation like the one in the video you've linked to, I suggest putting frontImageView and the backImageView directly on top of each other on the UIView you intend to flip. To start, set their images to front and back accordingly; and, in this particular case, hide the frontImageView and show the backImageView.

Assuming "card" is the UIView you intend to flip, to perform the flip try:

[UIView transitionWithView:card duration:0.65f
               options:UIViewAnimationOptionTransitionFlipFromRight animations:^{
                   frontImageView.hidden = NO;
                   backImageView.hidden = YES;
               } completion:^(BOOL finished) {
                   // whatever you'd like to do immediately after the flip completes


And to handle the shadow, first off, it appears in the video you posted that the shadow grows in length moreso than it just fades in. And it seems as if (and makes logical sense that) the shadow reaches its peak during the middle of the animation as the card is lifted at its highest point. Since the shadow grows then shrinks during the course of the flip animation, it doesn't make sense to include the shadow animation within the same animation block as the flip since they're on different time schedules.

Secondly with regard to the shadow, to animate the layer property, you have to use Core Animations.

Perhaps you can run the two animations concurrently, i.e. while the above animation is performing, also do something like:

CABasicAnimation *shadowAnimation = [CABasicAnimation animationWithKeyPath:@"shadowRadius"];
shadowAnimation.delegate = self;
[shadowAnimation setFromValue:[NSNumber numberWithFloat:3.0]];
[shadowAnimation setToValue:[NSNumber numberWithFloat:10.0]];
[shadowAnimation setDuration:0.65f];
shadowAnimation.autoreverses = YES;
[[card layer] addAnimation:shadowAnimation forKey:@"shadowRadius"];

The last portion has been adapted from this code and takes advantage of the autoreverse property to automatically reverse the shadow's growth.