Core Animation

Core Animation is an API that can be used to animate the views in your app.    Let’s make an app that has an image that we move around on the screen.  We are going to accomplish this buy using CALayer class, which can be used to animate image based content.

Start a new iOS Single View Application project in Xcode.  Select iPhone device in the drop-down menu.  We want to use storyboards and ARC in this project so make sure use storyboards and use automatic reference counting are checked.  Give it a name and save the project.

CALayer is part of the quartz framework, so we need to add the QuartzCore framework to our project.

Open ViewController.m and at the top import the quartz framework #import <QuartzCore/QuartzCore.h>  Find an image that you want to use in your animation and drag it to Xcode.  The name of my image is Sunshine.png, if you use a different name make the appropriate changes in your code.

Time to implement the viewDidLoad: method.  First we declare a UIImageView, setting its frame and adding it as a subview.


- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *sun = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Sunshine"]];

    [sun setFrame:CGRectMake(10.0, 10.0, 60.0, 60.0)];

    [self.view addSubview:sun];
}

If you run the app, you should be getting the following results:

To implement the animation we need to declare a CABasicAnimation, set the fromValue, toValue, and duration.  We also need to set the layer position to the toValue, otherwise the image will jump to its starting point when he animation completes.  And finally, we need to add the animation to the UIImageView layer.
We add the necessary changes to viewDidLoad:
- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *sun = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Sunshine"]];

    [sun setFrame:CGRectMake(10.0, 10.0, 60.0, 60.0)];

    [self.view addSubview:sun];

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.fromValue = [NSValue valueWithCGPoint:sun.layer.position];
    animation.toValue = [NSValue valueWithCGPoint:CGPointMake(250.0f, 250.0f)];
    animation.duration = 5.0f;
    sun.layer.position = CGPointMake(250.0f, 250.0f);
    [sun.layer addAnimation:animation forKey:@"AnimateFrame"];  
}

Run the app and you should see the image animate from the 10×10 point to the 250×250 point in 5 seconds.

Core Animation is very complicated topic, check the Core Animation Programming Guide.