UIKit Particle Systems in iOS 5 Tutorial

Ray Wenderlich

This post is also available in: Japanese, Russian

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

Update 10/24/12: If you’d like a new version of this tutorial fully updated for iOS 6 and Xcode 4.5, check out iOS 5 by Tutorials Second Edition!

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.

Ray Wenderlich

Ray is an indie software developer currently focusing on iPhone and iPad development, and the administrator of this site. He’s the founder of a small iPhone development studio called Razeware, and is passionate both about making apps and teaching others the techniques to make them.

When Ray’s not programming, he’s probably playing video games, role playing games, or board games.

User Comments

38 Comments

[ 1 , 2 , 3 ]
  • Can we make a line instead of these dots/fireballs ?
    Like If u swipe really fast the dots appear, Can the dots/fireballs be converted to a line between start and end point ?
    yunas
  • I want to make the stars follow a moving picture. The coordinates of the starting point of the target can reply but I can not for the stars.
    ageckil
  • Hi,
    very nice tutorial. can you tell me how can I show uiimageview or any view between animation and viewcontroller's view. right now id I add any view on viewcontroller animation goes behind that view
    prafulk007
  • I was wondering how to change the contents propery of the caemitterlayer? Does anyone know how to do that? I know how to do it for the birthrate and other scalar properties, but I can't figure this out.
    Soonerjk12
  • hi, how i can make flames light constantly? i want flames to light in particular shape, say question mark constantly.
    hitesh13
  • hi, i am using your code to store all the coordinate in an array. i want to display these coordinates on screen constantly. i am doing this by a code below,
    // this is the code from where i am calling a method "setEmitterPositionFromCoordinate".
    //self.coord is a nsmutablearray which is holding all coordinates in the form of cgpoint.
    for(int i=0;i<[self.coord count];i++)
    {
    [fireView setIsEmitting:YES];
    NSValue *val = [self.coord objectAtIndex:i];
    CGPoint p = [val CGPointValue];
    [fireView setEmitterPositionFromCoordinates:p];
    }
    //this is the method which i am calling.
    -(void)setEmitterPositionFromCoordinates: (CGPoint)p
    {
    fireEmitter.emitterPosition=CGPointMake(p.x, p.y);
    }

    but when i run this code, i get the last coordinate only emitted. kindly help so that i can emit all the coordinate.
    any kind of help would be appreciated.
    thanks in advance.
    hitesh13
  • Can I add the CALayer without the xib? I have a storyboard project.
    marciokoko
  • hallo, i would like to save the drawing i made with particles emitter in the photo album. Is it possible?
    tricgio
[ 1 , 2 , 3 ]

Other Items of Interest

Ray's Monthly Newsletter

Sign up to receive a monthly newsletter with my favorite dev links, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

Hang Out With Us!

Every month, we have a free live Tech Talk - come hang out with us!


Coming up in May: Procedural Level Generation in Games with Kim Pedersen.

Sign Up - May

Coming up in June: WWDC Keynote - Podcasters React! with the podcasting team.

Sign Up - June

Vote For Our Next Book!

Help us choose the topic for our next book we write! (Choose up to three topics.)

    Loading ... Loading ...

Our Books

Our Team

Tutorial Team

  • Jean-Pierre Distler
  • Felipe Laso Marsetti

... 55 total!

Editorial Team

... 21 total!

Code Team

  • Orta Therox

... 1 total!

Translation Team

  • Sonic Zhao
  • Team Tyran

... 38 total!

Subject Matter Experts

  • Richard Casey

... 4 total!