UIKit Particle Systems in iOS 5 Tutorial ( 附雨的粒子效果 )

原文地址: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:

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:

UIKit <wbr>Particle <wbr>Systems <wbr>in <wbr>iOS <wbr>5 <wbr>Tutorial(转载)

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:

UIKit <wbr>Particle <wbr>Systems <wbr>in <wbr>iOS <wbr>5 <wbr>Tutorial(转载)

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!

UIKit <wbr>Particle <wbr>Systems <wbr>in <wbr>iOS <wbr>5 <wbr>Tutorial(转载)

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:

UIKit <wbr>Particle <wbr>Systems <wbr>in <wbr>iOS <wbr>5 <wbr>Tutorial(转载)

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:

UIKit <wbr>Particle <wbr>Systems <wbr>in <wbr>iOS <wbr>5 <wbr>Tutorial(转载)

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:

UIKit <wbr>Particle <wbr>Systems <wbr>in <wbr>iOS <wbr>5 <wbr>Tutorial(转载)

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.

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];


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值