An iOS 4 iPad Core Animation Tutorial (Xcode 4)

PreviousTable of ContentsNext
Basic iPad Animation using Core Animation (Xcode 4)Integrating iAds into an iOS 4 iPad App (Xcode 4)


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


This chapter is dedicated to the creation of an iPad application that demonstrates the use of Core Animation. The end result is a simple application on which a colored square appears. When the user touches a location on the screen the box moves to that location. Through the use of affine transformations, the box will rotate 180 degrees as it moves to the new location whilst also changing in size. If you have not already read Basic iPad Animation using Core Animation it is recommended that you do so before proceeding with this tutorial.

Creating the Core Animation Project

Begin by launching Xcode and creating a new View-based iPad iOS application named animate.

Implementing the Interface File

For the purposes of this application we will need a UIView to represent the blue square and variables to contain the rotation angle and scale factor by which the square will be transformed. These need to be declared in the animateViewController.h file as follows:

#import <UIKit/UIKit.h>

@interface animateViewController : UIViewController {
        UIView *boxView;
        float   scaleFactor;
        float   angle;
}
@property (nonatomic, retain) UIView *boxView;
@end

Drawing in the UIView

Having declared the UIView reference we now need to initialize an instance object and draw a blue square located at a specific location on the screen. We also need to initialize our scaleFactor and angle variables and add boxView as a subview of the application’s main view object. These tasks only need to be performed once when the application first starts up so a good location is the loadView method which can be overridden by placing it in the animateViewController.m file. Note that we also need to synthesize access to boxView and release memory allocated to the outlet:

#import "animateViewController.h"

@implementation animateViewController
@synthesize boxView;
.
.
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
        scaleFactor = 2;
        angle = 180;
        CGRect frameRect = CGRectMake(10, 10, 100, 100);
        boxView = [[UIView alloc] initWithFrame:frameRect];
        boxView.backgroundColor = [UIColor orangeColor];
        [self.view addSubview:boxView];
}
.
.
- (void)dealloc
{
    [boxView release];
    [super dealloc];
}
.
.
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.boxView = nil;
}
.
.
@end

Detecting Screen Touches and Performing the Animation

When the user touches the screen the blue box needs to move from its current location to the location of the touch. During this motion, the box will rotate 180 degrees and change in size. The detection of screen touches was covered in detail in An Overview of iOS 4 iPad Multitouch, Taps and Gestures. For the purposes of this example we want to initiate the animation at the point that the user’s finger is lifted from the screen so need to implement the touchesEnded method in the animateViewController.m file:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch *touch = [touches anyObject];
   CGPoint location = [touch locationInView:self.view];
   [UIView beginAnimations:nil context:nil];
   [UIView setAnimationDelegate:self];
   [UIView setAnimationDuration:2];
   [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
   CGAffineTransform scaleTrans =
     CGAffineTransformMakeScale(scaleFactor, scaleFactor);
   CGAffineTransform rotateTrans = 
     CGAffineTransformMakeRotation(angle * M_PI / 180);
   boxView.transform = CGAffineTransformConcat(scaleTrans, rotateTrans);
   angle = (angle == 180 ? 360 : 180);
   scaleFactor = (scaleFactor == 2 ? 1 : 2);
   boxView.center = location;
   [UIView commitAnimations];
}

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

Before compiling and running the application we need to take some time to describe the actions performed in the above method. First, the method gets the UITouch object from the touches argument and the locationInView method of this object is called to identify the location on the screen where the touch took place:

UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self.view];

The animation block is then started and the current class declared as the delegate. The duration of the animation is set to 2 seconds and curve set to ease in/ease out:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

Two transformations are then generated for the view, one to scale the size of the view and one to rotate it 180 degrees. These transformations are then combined into a single transformation and applied to the UIView object:

CGAffineTransform scaleTrans =
  CGAffineTransformMakeScale(scaleFactor, scaleFactor);
CGAffineTransform rotateTrans = 
  CGAffineTransformMakeRotation(angle * M_PI / 180);
boxView.transform = CGAffineTransformConcat(scaleTrans, rotateTrans);

Ternary operators are then used to switch the scale and rotation angle variables ready for the next touch. In other words, after rotating 180 degrees on the first touch the view will need to be rotated to 360 degrees on the next animation. Similarly, once the box has been scaled by a factor of 2 it needs to scale back to its original size on the next animation:

angle = (angle == 180 ? 360 : 180);
scaleFactor = (scaleFactor == 2 ? 1 : 2);

Finally, the location of the view is moved to the point on the screen where the touch occurred before the animation is committed:

boxView.center = location;
[UIView commitAnimations];

Once the touchesEnded method has been implemented it is time to try out the application.

Building and Running the Animation Application

Once the all the code changes have been made and saved, click on the Run button in the Xcode toolbar. Once the application has compiled it will load into the iOS iPad Simulator (refer to Testing iOS 4 Apps on the iPad – Developer Certificates and Provisioning Profiles for steps on how to run the application on a physical iPad device).

When the application loads the orange square should appear near the top left hand corner of the screen. Click (or touch if running on a device) the screen and watch the box glide and rotate to the new location, the size of the box changing as it moves:

An iPad iOS 4 core animation example app running

Summary

Core Animation provides an easy to implement interface to animation within iOS 4 iPad applications. From the simplest of tasks such as gracefully fading out a user interface element to basic animation and transformations, Core Animation provides a variety of techniques for enhancing user interfaces. This chapter covered the basics of Core Animation before working step-by-step through an example to demonstrate the implementation of motion, rotation and scaling animation.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
Basic iPad Animation using Core Animation (Xcode 4)Integrating iAds into an iOS 4 iPad App (Xcode 4)