显示标签为“UIKit”的博文。显示所有博文
显示标签为“UIKit”的博文。显示所有博文

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

2011年11月14日星期一

UIKit Particle Systems in iOS 5 Tutorial

UIKit Particle Systems in iOS 5 Tutorial:
Let's end this feast with a tasty snack - UIKit Particle Systems in iOS 5!

Note from Ray: This is the fifteenth and final iOS 5 tutorial in the iOS 5 Feast! This tutorial is a free preview chapter from our new book iOS 5 By Tutorials. This Wednesday we’ll have our final post in the iOS 5 Feast series – the epic iOS 5 Feast Giveaway – so last chance for #ios5feast tweets! :]

This is a blog post by iOS Tutorial Team member Marin Todorov, a software developer with 12+ years of experience, an independant iOS developer and the creator of Touch Code Magazine.

You’ve probably seen particle systems used in many different iOS apps and games for explosions, fire effects, rain or snow falling, and more. However, you probably saw these types of effects most often in games, because UIKit didn’t provide a built-in capability to create particle systems – until iOS 5, that is!

Now with iOS 5, you can use particle systems directly in UIKit to bring a lot of exciting new eye-candy to your apps. Here are a few examples of where particle systems could be useful:

  • UIKit games: Yes, you can make games with plain UIKit (and some types of games work really well there, particularly card games and the like). But now, you can make them even better with explosions, smoke, and other goodies!
  • Slick UI effects: When your user moves around an object on the screen it can leave a trail of smoke, why not?
  • Stunning screen transitions: How about presenting the next screen in your app while the previous one disappears in a ball of fire?

Hopefully you’ve got some cool ideas of what you might want to use UIKit particle systems for. So let’s go ahead and try it out!

In this tutorial, we’re going to develop an app called “Draw with fire” that lets you (you guessed it) draw with fire on the screen.

I’ll take you along the process of creating the particle systems and having everything set on the screen, and you can develop the idea further into your own eye-candied drawing application. When the app is ready, you’ll be able to use it to draw a nice question mark of fire – like this one:

UIKit Particle Systems in iOS 5 Example



The New Particle APIs


The two classes you will need to use in order to create particle systems are located in the QuartzCore framework and are called CAEmitterLayer and CAEmitterCell.

The general idea is that you create a CAEmitterLayer, and add to it one or more CAEmitterCells. Each cell will then produce particles in the way it’s configured.

Also, since CAEmitterLayer inherits from CALayer, so you can easily inject it anywhere in your UIKit hierarchy!

I think the coolest thing about the new UIKit particle systems is that a single CAEmitterLayer can hold many CAEmitterCells. This allows you to achieve some really complicated and cool effects. For example, if you’re creating a fountain you can have one cell emitting the water and another emitting the vapor particles above the fountain!

Getting Started


Fire up Xcode (no pun intended) and from the main menu choose File\New\New Project. Select the iOS\Application\Single View Application template and click Next. Enter DrawWithFire for the product name, enter DWF for the class prefix, select iPhone for the Device Family, and make sure that “Use automatic reference counting” is checked (leave the other checkboxes unchecked). Click Next and save the project by clicking Create.

Select your project and select the DrawWithFire target. Open the Build Phases tab and open the Link Binary With Libraries fold. Click the plus button and double click QuartzCore.framework to add Quartz drawing capabilities to the project.

We’ll start the project by creating a custom UIView class which will have CAEmitterLayer as its layer. You can actually achieve this very very easy by overwriting the +(Class)layerClass method of the UIView class and returning a CAEmitter class. Pretty cool!

Create a new file with the iOS\Cocoa Touch\Objective-C class template, name the class DWFParticleView, and make it a subclass of UIView.

Open DWFParticleView.m and replace it with the following:


#import "DWFParticleView.h"
#import <QuartzCore/QuartzCore.h>

@implementation DWFParticleView
{
CAEmitterLayer* fireEmitter; //1
}

-(void)awakeFromNib
{
//set ref to the layer
fireEmitter = (CAEmitterLayer*)self.layer; //2
}

+ (Class) layerClass //3
{
//configure the UIView to have emitter layer
return [CAEmitterLayer class];
}

@end


Let’s go over the initial code:

  • We create a single private instance variable to hold our CAEmitterLayer.
  • In awakeFromNib we set fireEmitter to be the view’s self.layer. We store it in the fireEmitter instance variable we created, because we’re going to set a lot of parameters on this later on.
  • +(Class)layerClass is the UIView method which tells UIKit which class to use for the root CALayer of the view. For more information on CALayers, check out the Introduction to CALayer Tutorial.

Next let’s our view controller’s root view to DWFParticleView. Open up DWFViewController.xib and perform the following steps:

Setting a custom class in the Identity Inspector in Interface Builder

  1. Make sure the Utilities bar is visible (the highlighted button on the image above should be pressed down).
  2. Select the gray area in the Interface builder – this is the view controller’s root view.
  3. Click the Identity Inspector tab
  4. In the Custom class panel enter DWFParticleView in the text field.

At this point we have the UI all set – good job! Let’s add some particles to the picture.

A Particle Examined


In order to emit fire, smoke, waterfalls and whatnot you’ll need a good PNG file to start with for your particles. You can make it yourself in any image editor program; have a look at the one I did for this tutorial (it’s zoomed in and on a dark background so you can actually see the shape):

An example particle

My particle file is 32×32 pixels in size, it’s a transparent PNG file and I just used a little bit funkier brush to draw randomly with white color. For particles is best to use white color as the particle emitter will take care to tint the provided image in the colors we’d like to have. It’s also good idea to make particle image semi-transparent as the particle system can blend particles together by itself (you can figure out how it works by just trying out few different image files).

So, you can create a particle of your own or just use the one I made, but just be sure to add it to your Xcode project and have it named Particles_fire.png.

Let’s Start Emitting!


It’s time to add the code to make our CAEmitterLayer do its magic!

Open DWFParticleView.m, and add the following code at the end of awakeFromNib:


//configure the emitter layer
fireEmitter.emitterPosition = CGPointMake(50, 50);
fireEmitter.emitterSize = CGSizeMake(10, 10);


This sets the position of the emitter (in view local coordinates) and the size of the particles to spawn.

Next, add some more code to the bottom of awakeFromNib to add a CAEmitterCell to the CAEmitterLayer so we can finally see some particles on the screen!


CAEmitterCell* fire = [CAEmitterCell emitterCell];
fire.birthRate = 200;
fire.lifetime = 3.0;
fire.lifetimeRange = 0.5;
fire.color = [[UIColor colorWithRed:0.8 green:0.4 blue:0.2 alpha:0.1]
CGColor];
fire.contents = (id)[[UIImage imageNamed:@"Particles_fire.png"] CGImage];
[fire setName:@"fire"];

//add the cell to the layer and we're done
fireEmitter.emitterCells = [NSArray arrayWithObject:fire];


We’re creating a cell instance and setting up few properties. Then we set the emitterCells property on the layer, which is just an NSArray of cells. The moment emitterCells is set, the layer starts to emit particles!

Next set set some properties on the CAEmitterCell. Let’s go over these one by one:

  • birthRate: The number of emitted particles per second. For a good fire or waterfall you need at least few hundred particles, so we set this to 200.
  • lifetime: The number of seconds before a particle should disappear. We set this to 3.0.
  • lifetimeRange: You can use this to vary the lifetime of particles a bit. The system will give each individual a random lifetime in the range (lifetime – lifetimeRange, lifetime + lifetimeRange). So in our case, a particle will live from 2.5-3.5 seconds.
  • color: The color tint to apply to the contents. We choose an orange color here.
  • contents: The contents to use for the cell, usually a CGImage. We set it to our particle image.
  • name: You can set a name for the cell in order to look it up and change its properties at a later point in time.

Run the app, and check out our new particle effect!

A simple UIKit Particle Effect

Well it works, but isn’t as cool as we might like. You might barely even be able to tell it’s doing something, it just looks like an orange splotch!

Let’s change this a bit to make the particle effect more dynamic. Add this code just before calling setName: on the cell:


fire.velocity = 10;
fire.velocityRange = 20;
fire.emissionRange = M_PI_2;


Here we’re setting the following new properties on the CAEmitterCell:

  • velocity: The particles’s velocity in points per second. This will make our cell emit particles and send them towards the right edge of the screen
  • velocityRange: This is the range by which the velocity should vary, similar to lifetimeRange.
  • emissionRange: This is the angle range (in radians) in which the cell will emit. M_PI_2 is 45 degrees (and since this is the a range, it will be +/- 45 degrees).

Compile and run to check out the progress:

An expanding fan of particles

OK this is better – we’re not far from getting there! If you want to better understand how these properties affect the particle emitter – feel free to play and try tweaking the values and see the resulting particle systems.

Add two more lines to finish the cell configuration:


fire.scaleSpeed = 0.3;
fire.spin = 0.5;


Here we set two more properties on the CAEmitterCell:

  • scaleSpeed: The rate of change per second at which the particle changes its scale. We set this to 0.3 to make the particles grow over time.
  • spin: Sets the rotation speed of each particle. We set this to 0.5 to give the particles a nice spin.

Hit Run one more time:

An even cooler fan of particles

By now we have something like a rusty smoke – and guess what? CAEmitterCell has a lot more properties to tweak, so kind of the sky is the limit here. But we’re going to leave it like that and go on with setting some configuration on the CAEmitterLayer. Directly after setting fireEmitter.emitterSize in the code add this line:


fireEmitter.renderMode = kCAEmitterLayerAdditive;


This is the single line of code which turns our rusty smoke into a boiling ball of fire. Hit Run and check the result:

Changing the render mode to additive results in a cool glowing effect

What’s happening? The additive render mode basically tells the system not to draw the particles one over each other as it normally does, but to do something really cool: if there are overlapping particle parts – their color intensity increases! So, in the area where the emitter is – you can see pretty much a boiling white mass, but at the outer ranges of the fire ball – where the particles are already dying and there’s less of them, the color tints to it’s original rusty color. Awesome!

Now you might think this fire is pretty unrealistic – indeed, you can have much better fire by playing with the cell’s properties, but we need such a thick one because we’re going to draw with it. When you drag your finger on the device’s screen there’s relatively few touch positions reported so we’ll use a thicker ball of fire to compensate for that.

Play With Fire!


Now you finally get to play with fire (even though you’ve been told not to your entire life!) :]

To implement drawing on the screen by touching we’ll need to change the position of the emitter according to the user’s touch.

First declare a method for that in DWFParticleView.h:


-(void)setEmitterPositionFromTouch: (UITouch*)t;


Then implement the method in DWFParticleView.m:


-(void)setEmitterPositionFromTouch: (UITouch*)t
{
//change the emitter's position
fireEmitter.emitterPosition = [t locationInView:self];
}


This method gets a touch as a parameter and sets the emitterPosition to the position of the touch inside the view – pretty easy.

Next we’ll need an outlet for our view so we can tweak it from the view controller. Open DWFViewController.h and replace the code with the following:


#import <UIKit/UIKit.h>
#import "DWFParticleView.h"

@interface DWFViewController : UIViewController
{
IBOutlet DWFParticleView* fireView;
}
@end


As you see we import our custom view class and we declare an instance variable for the DWFParticleView.

Next open DWFViewController.xib and control-drag from the File’s Owner to the root view, and choose fireView from the popup:

Connecting the view to an outlet in Interface Builder

Now we can access the emitter layer from the view controller. Open DWFViewController.m, remove all the boilerplate methods from the implementation, and add this instead:


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[fireView setEmitterPositionFromTouch: [touches anyObject]];
}


Now hit Run – touch and drag around and you’ll see the emitter moving and leaving a cool trail of fire! Try dragging your finger on the screen slower or faster to see the effect it generates.

A cool trail of fire

Dynamically Modifying Cells


The last topic for today will be modifying cells in an emitter layer dynamically. Right now the emitter emits particles all the time, and that’s not really giving the feel to the user that they’re really drawing on the screen. Let’s change that by emitting particles only when there’s a finger touching the screen.

Start by changing the birthRate of the cell at creation time to “0″ in DWFParticleView.m’s awakeFromNib method:


fire.birthRate = 0;


If you run the app now, you should see an empty screen. Good! Now let’s add a method to turn on and off emitting. First declare the method in DWFParticeView.h:


-(void)setIsEmitting:(BOOL)isEmitting;


Then implement it in DWFParticleView.m:


-(void)setIsEmitting:(BOOL)isEmitting
{
//turn on/off the emitting of particles
[fireEmitter setValue:[NSNumber numberWithInt:isEmitting?200:0]
forKeyPath:@"emitterCells.fire.birthRate"];
}


Here we’re using the setValue:forKeyPath: method so we can modify a cell that’s already been added to the emitter by the name we set earlier. We use “emitterCells.fire.birthRate” for the keypath, which means the birthRate property of the cell named fire, found in the emitterCells array.

Finally we’ll need to turn on the emitter when a touch begins and turn it off when the user lifts their finger. Inside DWFViewController.m add:


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[fireView setEmitterPositionFromTouch: [touches anyObject]];
[fireView setIsEmitting:YES];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[fireView setIsEmitting:NO];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
[fireView setIsEmitting:NO];
}


Compile and run the project, and watch out – you’re playing with fire! :]

An apple made with fire!  :]

Where To Go From Here?


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

If you’ve enjoyed this tutorial, there’s a lot more you can play around with from here! You could:

  • Experiment with different particle image files
  • Go through CAEmitterCell reference docs and have a look at all its properties
  • Add functionality to render the image on the screen to a file
  • Capture the drawing as a video file
  • Add burning flames behind all your text labels in all your apps ;]

And this concludes our free tutorials in the iOS 5 Feast iOS 5 Tutorial Month! If you enjoyed these tutorials, be sure to check out our book iOS 5 By Tutorials, where we have tons of cool new iOS 5 tutorials for you!

Stay tuned for this Wednesday, where we will be announcing the winners of the epic iOS 5 Feast giveaway (over $600 in value)! It’s your last chance to enter (by sending one or more tweets with the hashtag #ios5feast), so be sure to do so if you haven’t already!

Also if you have any comments or questions on this tutorial or on UIKit Particle Systems in general, please join the forum discussion below!

This is a blog post by iOS Tutorial Team member Marin Todorov, a software developer with 12+ years of experience, an independant iOS developer and the creator of Touch Code Magazine.

UIKit Particle Systems in iOS 5 Tutorial is a post from: Ray Wenderlich