2011年11月22日星期二

UIView Animation Tutorial: Practical Recipes

UIView Animation Tutorial: Practical Recipes:
Use some UIView Animation Recipes you can use in your apps!
Use some UIView Animation Recipes you can use in your apps!

This is a blog post by iOS Tutorial Team member Fabio Budai, an Objective C developer from Italy.

One lesson I learned the hard way is that graphics and animations are really important in iPhone Apps, and not only in games. Utilities also need a nice UI and some cool graphic effects.

It may be true that most of these animations are useless! At least when it comes to functionality. But being “good-looking” can be the small and winning difference between your app and the competitor’s.

Sometimes your design needs a complex UI that can contain a lot more objects than you can fit on a screen. A good solution to this problem is to display parts of your interface only as needed (stuff like pickers, keyboards, extra buttons…). Again, these items must show up with cool effects to make the app seem polished.

Luckily, UIKit has some really powerful built-in animations, and in iOS 4, blocks make using them really easy.

We already covered how to use UIView Animations in the UIView Animation Tutorial posted here almost a year ago, so you might want to go through that tutorial first.

This tutorial takes things a step further by giving some practical examples and recipes for how you can use UIView Animations in your own apps, to add some polish and spice!



Getting Started


Create a new project in XCode: File\New\New Project. Pick the Single View Application template and call it UIAnimationSamples.

Make sure you check ARC and Storyboard. Even if in this tutorial we won’t be focusing on these new technologies, it is a good practice to keep all your new projects up-to-date. In any case, you can use almost all of the code in this tutorial “as is” in pre-ARC projects.

Create a new file (File\New\New File) and choose the iOS\Cocoa Touch\Objective-C category template. Enter “Animation” for the Category and “UIView” for Category on, and finish creating the file. A category allows us to add some methods to an already existing class (UIView in this case) without subclassing it: a very neat and powerful way to expand an object’s functionality. We’ll put all the animation code this category.

Add the following code inside the interface in UIView+Animation.h:


- (void) moveTo:(CGPoint)destination duration:(float)secs option:(UIViewAnimationOptions)option;


Then add the implementation in UIView+Animation.m as follows:


- (void) moveTo:(CGPoint)destination duration:(float)secs option:(UIViewAnimationOptions)option
{
[UIView animateWithDuration:secs delay:0.0 options:option
animations:^{
self.frame = CGRectMake(destination.x,destination.y, self.frame.size.width, self.frame.size.height);
}
completion:nil];
}


This adds a new method to ALL instances of UIView that moves the view itself from its current position to the new destination in “secs” (seconds; it’s a float, so you have a fine control of duration). The option relates to the animation curve used (more on this later). For now, we’ll use the default value of zero.

How does this work? Our code uses the [UIView animateWithDuration:] API on one of the properties of a UIView that can be animated: the frame. By simply changing it in the block “animations,” you tell Core Animation to move it to the new coordinates, taking “secs” time in doing it, and automatically calculate (and draw) all the intermediate “steps” to get a smooth animation.

It’s as easy as that: you just set the new position and the framework will animate it moving in a straight line to the destination! Let see this in action by adding some code to the view controller.

Replace ViewController.h with the following:


#import <UIKit/UIKit.h>
#import "UIView+Animation.h"

@interface ViewController : UIViewController
@property (nonatomic,weak) IBOutlet UIButton *movingButton;

- (IBAction) btnMoveTo:(id)sender;

@end


This simply declares a button that we’ll make move around the screen, and a method that will start the button moving. We’ll add the GUI for this later.

Then, make the following changes to ViewController.m:


// Add right after @implementation
@synthesize movingButton;

// Add right before @end
#pragma mark - animation actions

- (IBAction) btnMoveTo:(id)sender
{
UIButton* button= (UIButton*)sender;
[movingButton moveTo:
CGPointMake(button.center.x - (movingButton.frame.size.width/2),
button.frame.origin.y - (movingButton.frame.size.height + 5.0))               
duration:1.0 option:0]; // above the tapped button
}


To see the result, we need to execute just one final step: add the controls in the View.

Open up MainStoryboard.storyboard, and change the background color of the View to dark blue. Then drop a Round Rect button anywhere inside the View and set its title to “Here”. Then Control-click on the button, drag from the “Touch Up Inside” action to the View Controller, and connect it to the “btnMoveTo” method. Then make three copies of this button and place them around the View (one easy way to do this is to Option-drag the button).

Finally, add another Round Rect button to the center of the view, and set its type to Custom. Use this arrow as the image, set the width and height to 50 pixels. Control-click the View Controller and drag a line from the movingButton outlet to this new button to connect it.

Your storyboard should now look something like this (but it’s OK if your buttons are in different positions):



Now build and run! The arrow will move above the “Here” button. Pretty cool for just a few lines of code, eh?



This recipe is useful to highlight the user selection (like the small blue triangle in the Twitter app) or to slide in a bigger view (you put just a small part of a view onscreen, and allow the user to slide the rest of the view into the screen by tapping the arrow).

CGAffineTransform


Probably the most powerful animatable property on UIView is transform, which takes a CGAffineTransform. This is a matrix that expresses how each pixel of the UIView should be modified, applying some math formulas.

Don’t worry, you don’t actually have to remember linear algebra, because there are some built-in CGAffineTransforms to make life nice and simple. We’ll focus on two of them:

  • CGAffineTransformScale: Allows you to scale a view up or down, optionally using different factors for the x and y axes. A value of 10.0 means “make the view 10 times bigger than the actual frame.” Please note that applying this transform may invalidate the Frame property.
  • CGAffineTransformRotate: Allows you to rotate a view by a given angle. It uses radians, the standard unit of angular measure. One radian is equal to 180/π degrees.

It is important to understand how animation of transforms works: you can combine multiple transforms of different kinds, but iOS will “see” only the final result. So if you make a 360° (2π radians) rotation, the net effect is no rotation at all, and you won’t see any animation on your view!

Keep in mind that:

  • Rotations up to 180° are animated clockwise
  • Rotations from 180° to 360° are animated counter-clockwise (it takes the shortest path, so 270° is rendered as a -90° rotation)
  • All rotations over a complete circle (360°) are ignored, and a 2π module is applied

This will be easy to see when you try it out – so let’s see rotation in action!

In UIView+Animation.h, add the following inside the @interface:


- (void) downUnder:(float)secs option:(UIViewAnimationOptions)option;


And then add the implementation in UIView+Animation.m:


- (void) downUnder:(float)secs option:(UIViewAnimationOptions)option
{
[UIView animateWithDuration:secs delay:0.0 options:option
animations:^{
self.transform = CGAffineTransformRotate(self.transform, M_PI);
}
completion:nil];
}


This simply animates the view to rotate 180° over the specified number of seconds.

Add a new method that will run this rotation in ViewController.h:


- (IBAction) btnDownUnder:(id)sender;


Then add the implementation in ViewController.m:


- (IBAction) btnDownUnder:(id)sender
{
UIButton* button= (UIButton*)sender;
[button downUnder:1.0 option:0];
}


And finally, open up MainStoryboard.storyboard, control-click the button, and drag a line from the “Touch Up Inside” action to the View Controller and connect it to the btnDownUnder method.

Run the app. Every time you tap the arrow button, you should see it flipping up/down (rotating 180°) with a smooth rotation. And you can still move it around!

This recipe may be useful for something like an on/off switch. You can play with different angles to generate arrows for different directions using just one image.

A scale transformation is perfect for creating a zoom effect that can be great for pickers. And a picker is exactly what we need in the next section!

Animation Curves


If you pay close attention to the animation we just coded, you’ll notice that the arrow starts slow, then speeds up, then slows down again until it stops (you can raise the duration to better see this effect).

What you are seeing is the default “curve” for UIView animations. Curves are actually acceleration curves that describe the speed variations of the animation. There are 4 curves available:

  • UIViewAnimationOptionCurveEaseInOut: start slow, speed up, then slow down
  • UIViewAnimationOptionCurveEaseIn: start slow, speed up, then suddenly stop
  • UIViewAnimationOptionCurveEaseOut: start fast, then slow down until stop
  • UIViewAnimationOptionCurveLinear: constant speed

UIViewAnimationOptionCurveEaseInOut is the default because the effect seems very “natural.” But of course, “natural” depends on what you want to do.

To play with different curves we can simply use the corresponding constant as an “option” parameter. But since we’re still learning what they do, let’s build a “curve picker” to try them all out!

iPhone pickers are somewhat ugly objects that eat lots of space and give a generally poor user experience. A good solution is to create a custom, good-looking picker view that’s shown only when necessary (automatically or when the user tap on a button). We’ll use the scale transform to bring up the picker with a cool zoom animation.

We need some more code to made this work, but please note that most of it is for handling the picker: the animations are still made with just 2-3 lines of code.

First we add the zoom animations in UIView+Animation.m, and this time we’ll animate the adding/removing of a subview:


- (void) addSubviewWithZoomInAnimation:(UIView*)view duration:(float)secs option:(UIViewAnimationOptions)option
{
// first reduce the view to 1/100th of its original dimension
CGAffineTransform trans = CGAffineTransformScale(view.transform, 0.01, 0.01);
view.transform = trans; // do it instantly, no animation
[self addSubview:view];
// now return the view to normal dimension, animating this tranformation
[UIView animateWithDuration:secs delay:0.0 options:option
animations:^{
view.transform = CGAffineTransformScale(view.transform, 100.0, 100.0);
}
completion:nil]; 
}

- (void) removeWithZoomOutAnimation:(float)secs option:(UIViewAnimationOptions)option
{
[UIView animateWithDuration:secs delay:0.0 options:option
animations:^{
self.transform = CGAffineTransformScale(self.transform, 0.01, 0.01);
}
completion:^(BOOL finished) {
[self removeFromSuperview];
}];
}


This is similar to the rotate transform we ran earlier, except it uses a scale transform instead of a rotate transform. It also adds and removes the new subview as appropriate.

Next add the definitions in UIView+Animation.h:


- (void) addSubviewWithZoomInAnimation:(UIView*)view duration:(float)secs option:(UIViewAnimationOptions)option;
- (void) removeWithZoomOutAnimation:(float)secs option:(UIViewAnimationOptions)option;


OK, we’re done with the zoom animation code. Now let’s create the curve picker!

Create a new file with the iOS\Cocoa Touch\Objective-C class template, name the Class AnimationCurvePicker and make it a subclass of UIView. To make it easy to layout, also create a XIB where we can design the view, by creating another file with the iOS\User Interface\View template (name it AnimationCurvePicker.xib).

The code we’ll add to AnimationCurvePicker class is pretty simple: we’ll add a method to loads the xib and set the delegate (that will be the ViewController, of course).

So open up AnimationCurvePicker.h and replace it with the following:


#import <UIKit/UIKit.h>

@interface AnimationCurvePicker : UIView
@property (nonatomic,weak) IBOutlet UITableView *animationlist;

+ (id) newAnimationCurvePicker:(id)pickDelegate;
@end


Then replace AnimationCurvePicker.m with the following:


#import "AnimationCurvePicker.h"

@implementation AnimationCurvePicker
@synthesize animationlist;

+ (id) newAnimationCurvePicker:(id)pickerDelegate
{
UINib *nib = [UINib nibWithNibName:@"AnimationCurvePicker" bundle:nil];
NSArray *nibArray = [nib instantiateWithOwner:self options:nil];
AnimationCurvePicker *me = [nibArray objectAtIndex: 0];
me.animationlist.delegate = pickerDelegate;
me.animationlist.dataSource = pickerDelegate;
return me;
}

@end


Then open up AnimationCurvePicker.xib, change the view class to AnimationCurvePicker, set the status bar to “none” and modify the frame to 280 width and 300 height.

Next, add a table view of the same dimensions, and set the style to grouped. Control-click the view (“Animation Curve Picker”) and drag a line from the animation list outlet to the Table View.

It should look like this:



Finally, you need to make some modifications to ViewController.h. I’ve included the entire file here for easier editing:


#import <UIKit/UIKit.h>
#import "UIView+Animation.h"
#import "AnimationCurvePicker.h"

@interface ViewController : UIViewController {
NSMutableArray *curvesList;
int selectedCurveIndex;
UIView *pickerView;
}

@property (nonatomic,weak) IBOutlet UIButton *movingButton;

- (IBAction) btnMoveTo:(id)sender;
- (IBAction) btnDownUnder:(id)sender;
- (IBAction) btnZoom:(id)sender;

@end


Next, make the following changes to ViewController.m:


/// put this just under @synthesize...
static int curveValues[] = {
UIViewAnimationOptionCurveEaseInOut,
UIViewAnimationOptionCurveEaseIn,
UIViewAnimationOptionCurveEaseOut,
UIViewAnimationOptionCurveLinear };

/// Replace vieDidLoad with the following
- (void)viewDidLoad
{
[super viewDidLoad];
curvesList = [[NSMutableArray alloc] initWithObjects:@"EaseInOut",@"EaseIn",@"EaseOut",@"Linear", nil];
selectedCurveIndex = 0;
}

/// modify previous IBAction methods to pass the curve to animation
- (IBAction) btnMoveTo:(id)sender
{
UIButton* button= (UIButton*)sender;
[movingButton moveTo:
CGPointMake(button.center.x - (movingButton.frame.size.width/2),
button.frame.origin.y - (movingButton.frame.size.height + 5.0))               
duration:1.0
option:curveValues[selectedCurveIndex]]; // above the tapped button
}

- (IBAction) btnDownUnder:(id)sender
{
UIButton* button= (UIButton*)sender;
[button downUnder:1.0 option:curveValues[selectedCurveIndex]];
}

/// Then add the following lines:
- (IBAction) btnZoom:(id)sender
{
UIButton* button= (UIButton*)sender;
pickerView = [AnimationCurvePicker newAnimationCurvePicker:self];
// the animation will start in the middle of the button
pickerView.center = button.center;
[self.view addSubviewWithZoomInAnimation:pickerView duration:1.0 option:curveValues[selectedCurveIndex]];
}

#pragma mark - animation curves picker
// handling the picker, that is a simple tableview in this example
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [curvesList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];

if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text = [curvesList objectAtIndex:indexPath.row];

if (indexPath.row == selectedCurveIndex)
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;

return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"Select the Animation Curve to be used";
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
return @"Curves will not affect total duration but instant speed and acceleration";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
if (selectedCurveIndex != indexPath.row)
{
NSIndexPath *oldPath = [NSIndexPath indexPathForRow:selectedCurveIndex inSection:indexPath.section];
cell = [tableView cellForRowAtIndexPath:oldPath];
cell.accessoryType = UITableViewCellAccessoryNone;

selectedCurveIndex = indexPath.row;
}

if (pickerView)
{
[pickerView removeWithZoomOutAnimation:1.0 option:curveValues[selectedCurveIndex]];
pickerView = nil;
}
}


Last step: in MainStoryboard.storyboard, add a button somewhere near the middle of the View, put “Picker” as Text and connect it to “btnZoom:” method of File Owner.

With this code, we create a custom view “AnimationCurvePicker” derived from UIView that contains a tableview, then delegate the ViewController to manage user choices, and we use the selected values to change the Animation Curve used by all the animations we made.

On top of this, we animate the addition of this subview with a zoom animation.

This recipe can be useful if you want to bring up a popup control in your app, and of course the animation curves themselves can be useful for all sorts of effects.

Run the app, and play around with the different animation curves!



Making Your Own Transform


To create really complex gaming-type animations, it’s probably better to use OpenGL or Cocos2D, but don’t underestimate the power of UIKit.

Also keep in mind that another property you can animate is the Alpha Channel. This makes it really easy to create fade effects, which is another nice way to add/remove subview.

Now we’ll add another button to the main View that will bring in a HUD-like view with a fade-in animation. This view will have a “STOP” button that dismisses the animation with a funny “draining the sink” custom effect!

First import this FakeHUD.png image into your project, then add a new Objective C class called FakeHUD, derived from UIView. Why “fake”? Because it only pretends to look like a HUD, when it’s actually just a full screen view… ;)

Let’s code!

Replace FakeHUD.h with the following:


#import <UIKit/UIKit.h>
#import "UIView+Animation.h"

@interface FakeHUD : UIView

- (IBAction)btnStop;
+ (id) newFakeHUD;
@end


Replace FakeHUD.m with the following:


#import "FakeHUD.h"

@implementation FakeHUD
// create a new view from the xib
+ (id) newFakeHUD
{
UINib *nib = [UINib nibWithNibName:@"FakeHUD" bundle:nil];
NSArray *nibArray = [nib instantiateWithOwner:self options:nil];
FakeHUD *me = [nibArray objectAtIndex: 0];
return me;
}

- (IBAction)btnStop
{
// the following method will be defined and explained later: ignore the warning
[self removeWithSinkAnimation:40];
}
@end


Now add a xib named FakeHUD.xib (with the iOS\User Interface\View template) and change the class of the main UIView in FakeHUD. Set the simulated status bar to “none,” and change the background color to “clear.”

Add an UIImageView, set FakeHUDD.png as the image, and again change the backgound color to clear. After that, put a couple of labels in the bigger circle (they pretend to be the messages for the user) and a big white Activity Indicator (check the “Animating” flag).

Put a UIButton (type “custom”) in the smaller circle, with “STOP” as the text, change the text color to white, and connect “the tap up inside” event to the btnStop: IBAction of the FakeHUD view.

With this, the HUD is complete, and should look like this:



Now the “draining the sink” animation, finally!

Add to UIView+Animation.h:


- (void) addSubviewWithFadeAnimation:(UIView*)view duration:(float)secs option:(UIViewAnimationOptions)option;
- (void) removeWithSinkAnimation:(int)steps;
- (void) removeWithSinkAnimationRotateTimer:(NSTimer*) timer;


And the implementation in UIView+Animation.m:


// add with a fade-in effect
- (void) addSubviewWithFadeAnimation:(UIView*)view duration:(float)secs option:(UIViewAnimationOptions)option
{
view.alpha = 0.0; // make the view transparent
[self addSubview:view]; // add it
[UIView animateWithDuration:secs delay:0.0 options:option
animations:^{view.alpha = 1.0;}
completion:nil]; // animate the return to visible 
}

// remove self making it "drain" from the sink!
- (void) removeWithSinkAnimation:(int)steps
{
NSTimer *timer;
if (steps > 0 && steps < 100) // just to avoid too much steps
self.tag = steps;
else
self.tag = 50;
timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(removeWithSinkAnimationRotateTimer:) userInfo:nil repeats:YES];
}
- (void) removeWithSinkAnimationRotateTimer:(NSTimer*) timer
{
CGAffineTransform trans = CGAffineTransformRotate(CGAffineTransformScale(self.transform, 0.9, 0.9),0.314);
self.transform = trans;
self.alpha = self.alpha * 0.98;
self.tag = self.tag - 1;
if (self.tag <= 0)
{
[timer invalidate];
[self removeFromSuperview];
}
}


Before adding the code to put this into action, I want to explain the method in-depth.

This animation is based on progressive transformations applied a fixed number of times – each 1/20th of a second. It uses an NSTimer and stores the remaining steps in the Tag property (with Category we can only add new methods, not new objects/variables, so we use an existing one for keeping it simple). The right number of steps depends on how long you want this to last and how big your view is: you need some heuristic tests to find the right value.

At each step 2, CGAffineTransform (scale and rotate) are applied to the actual Transform property of the UIView, so that it’s reduced and rotated a bit. As a final effect, it’s also made a little lighter via Alpha Channel: in this way you’ll see your view quickly sinking while spinning, like someone took the stopper out of a sink full of water!

After the last step is done, the timer is invalidated and the view removed from the superview.

To see this in action, we just need to put one more button in ViewController and use the above animations.

Make the following changes to ViewController.h:


// Add to top of file
#import "FakeHUD.h"

// Add to method list
- (IBAction) btnHUD:(id)sender;


As always, implement it in ViewController.m:


- (IBAction) btnHUD:(id)sender
{
FakeHUD *theSubView = [FakeHUD newFakeHUD];
[self.view addSubviewWithFadeAnimation:theSubView duration:1.0 option:curveValues[selectedCurveIndex]];
}


In View in the MainStoryboard.storyboard, add a button with text “HUD” and connect the “tap up inside” event to (IBAction) btnHUD:.

Now you can run the app and enjoy!



Where To Go From Here?


Here is a example project with all of the code from the above tutorial.

UIKit provides quite a powerful way to animate views, and playing with the properties can give you some really cool effects with only a few lines of code. These effects are perfect for tool/utility-type apps, and adding them as categories of UIView makes your code more readable and lets you focus on your application logic.

I hope you enjoy your experimentations with UIView animations, and look forward to seeing you use them in your apps!

If you have any questions or comments about UIView animation, please join the forum discussion below!



This is a blog post by iOS Tutorial Team member Fabio Budai, an Objective C developer from Italy.

UIView Animation Tutorial: Practical Recipes is a post from: Ray Wenderlich

没有评论:

发表评论