原文地址:http://www.raywenderlich.com/6063/uikit-particle-systems-in-ios-5-tutorial?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+RayWenderlich+(Ray+Wenderlich+|+iPhone+Developer+and+Gamer)
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:
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:
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 .
Next let’s our view controller’s root view to DWFParticleView. Open up DWFViewController.xib and perform the following steps:
- Make sure the Utilities bar is visible (the highlighted button on the image above should be pressed down).
- Select the gray area in the Interface builder – this is the view controller’s root view.
- Click the Identity Inspector tab
- 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):
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 , 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:
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!
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!
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:
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:
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:
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:
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:
This is the single line of code which turns our rusty smoke into a boiling ball of fire. Hit Run and check the result:
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.
1->雨的粒子效果
ParticleRain *rain = [[ParticleRain alloc] init]; rain.speed = 200; rain.speedVar = 30; rain.angle = -60; rain.angleVar = 10; rain.size = 5; rain.sizeVar = 1; rain.emissionRate = 120; rain.position = cpv(320, 160); rain.posVar = cpv(160 + 80, 0); [self addChild: rain z:10];