Thursday, February 21, 2013

iPhone Animation Blocks

The demo in action!
Animating with blocks of code is now one of the easiest things to do in iPhone programming. You must wrap your head around the code style (sort of like using Lambda expressions in C#.) Once you do, it's a snap to add really cool animations to your apps.

Download Sample App

I've attached a quick sample app that shows how to animate an image. The example expands and fades-out an image when you click on it. The magic is in the following code:

      // Create animation with two animation functions: alpha and image size  
   [UIView animateWithDuration:1.0  
                                delay: 0.0  
                               options: UIViewAnimationOptionCurveEaseIn  
                           animations:^{  
                                imgMain.alpha = 0.0;  
                                imgMain.bounds = newSize;  
                           }  
                           completion:^(BOOL finished){  
                                // Now fade it back in to the right size  
                                [UIView animateWithDuration:1.0  
                                                          delay: 0.0  
                                                         options:UIViewAnimationOptionCurveEaseOut  
                                                    animations:^{  
                                                         imgMain.alpha = 1.0;  
                                                         imgMain.bounds = origSize;  
                                                    }  
                                                    completion:nil];  
                           }];  

Note how we can add any number of animations to the block and they all will be executed at the same time. We also can specify what happens when each animation completes.  It is a lot like using the CAAnimationGroup, but in my opinion, much easier.

No comments:

Post a Comment