Uikit Particle System tutorial in iOS 5 (produced by tairan Translation Team)

Source: Internet
Author: User
Tags emit uikit

Disclaimer (read only !) : The original translations of all tutorials provided by this blog are from the Internet and are only for learning and communication purposes. Do not conduct commercial communications. At the same time, do not remove this statement when reprinting. In the event of any dispute, it has nothing to do with the owner of this blog and the person who published the translation. Thank you for your cooperation!


Original article address:Http://www.raywenderlich.com/6063/uikit-particle-systems-in-ios-5-tutorial


This document consistsTranslation of sugar fried shrimps and benna, Proofreading: Sai, u0u0, iven, and Zilong Mountain


IOS 5InUikitParticle System tutorial

 

Ray's words: This is 15th and the last iOS 5 tutorial in the iOS 5 feast! This tutorial is a free preview section in our new book "iOS 5 tutorial. This week, we will see the last release of the "iOS 5 feast" series-from the epic "iOS 5 feast" and the last broadcast of # ios5feast! :]

This is a tutorial written by Marin Todorov, a member of the IOS tutorial team. He is a software developer with over 12 years of experience and an independent IOS developer, he is also the creator of touch Code magazine.

You may have seen some particle systems that have been applied to many IOS applications.ProgramAnd games, such as explosion, fire effects, rain or snow. However, most of the effects you see may appear in the game, because uikit does not provide built-in functions to create a particle system-until iOS 5 appears, this situation will change, this tutorial uses uikit to create a particle system!

Now, with iOS 5, you can directly use the Particle System in uikit to bring a lot of exciting visual enjoyment to your applications. Here are some examples that apply very well to particle systems:

    • Uikit games: Yes, you can make games through general uikit (some games work quite well, especially card and board games ). Now, you can make better games with explosion, smoke, and other more attractive things!
    • Beautify the UI: when your user moves an object on the interface, it can leave a smoke trace. Why not?
    • Dazzling screen transition: why not let the previous scene disappear into a fireball when your application shows the next scene?

I hope you can do something with the uikit particle system. Maybe you already have some cool ideas. Let's get started!

In this tutorial, we will develop an application called "draw with fire" to draw a flame on the screen.

You will work with me to create and set the particle system to achieve the effect on the screen, so that you can implement your ideas step by step. When this application is completed, you can use it to draw a beautiful question mark marked with a flame, just like this:

 

 

New ParticleAPI

 

Two classes will be used when you create a particle system. They are named caemitterlayer and caemittercell in the quartzcore framework.

The general idea is that you create a caemitterlayer and add one or more caemittercells to it. Then, each cell generates particles according to the style it is configured.

Besides, caemitterlayer inherits from calayer. You can easily add it anywhere in the uikit hierarchy!

I think the coolest thing about this new uikit particle system is that a separate caemitterlayer can support multiple caemittercells. This allows you to complete some very complex and cool results. For example, when you create a spring water, you can have a cell that emits water drops, and another cell emits water vapor on the spring water!

 

Getting started

 

Open xcode, select file \ new project from the main menu, select IOS \ Application \ single view application template, click Next, and type the program name "drawwithfire ", type the prefix of "DwF", select "iPhone for Device Family", and check "use automatic reference counting" (select another option ). Click next, and then click Create to save the project.

Select your project, and then select the target of drawwithfire. Next, open the build phases tab, expand the link binary with libraies section, click "+", double-click quartzcore. Framework, and add the quartz drawing function to the project.

We will create a custom uiview class to start the project. This class will have caemitterlayer as its layer. In fact, it is very simple to do this by rewriting the + (class) layerclass method of the uiview class and returning a caemitter class. Pretty cool!

Create a new file using the IOS \ cocoa Touch \ objective-C class template. The class name is dwfparticipant view and inherits from uiview.

Open dwfparticipant view. M and replace it with the followingCode:

# Import " Dwfparticipant leview. h  " 
# Import <quartzcore/quartzcore. h>

@ Implementation dwfparticipant leview
{
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 repeat the initial code:

    • We create a single private instance variable to control the caemitterlayer.
    • In awakefromnib, we set fireemitter as the self. layer of this view. We store it in the fireemitter instance variable we created, because we will set many parameters on it later.
    • + (Class) layerclass is the class method of uiview. It tells uikit which class is used as the root calayer of the view. For more information about calayer, see the calayer tutorial.

 

Next, let's switch the Root View of the View Controller to dwfparticipant view. Open dwfviewcontroller. XIB and perform the following steps:

 

1. confirm that the utilities toolbar is visible (the highlighted buttons in this figure are changed to being pressed ).

2. Select the gray area in interface builder-this is the root view of this view controller.

3. Click the identity Inspector tab.

4. On the custom class panel, enter dwfparticipant view in the text box.

 

Now, we have set all the UIS-well done! Let's add some particles in the graph.

 

AParticle examined

 

To emit flame, smoke, waterfall, or anything else, you will need a good PNG file to start your particles. You can create it yourself in any image editing program. Take a look at the image I created for this tutorial (it is enlarged and placed in a black background so that you can see its shape clearly ):

 

The size of my particle file is 32*32 pixels, which is a transparent PNG file. I only use a trendy brush and draw it in White at will. For particles, the best thing is to use white because the particle transmitter can color the provided image with the color we want. It is also a good idea to make the particle image translucent, so that the particle system can mix the particles themselves together (you can understand how it works through a few different image files ).

 

.

 

Let's start generating particles!

It's time to add code to let our caemitterlayer do some amazing things!

Open dwfparticipant view. M and add the following code to awakefromnib:

//Configure the emitter layer
Fireemitter. emitterposition = cgpointmake (50,50);
Fireemitter. emittersize = cgsizemake (10,10);

 

The above code is used to set the emitter coordinates (under the view coordinate system) and the size of the generated particles.

Then, add a caemittercell to the caemitterlayer after awakefromnib, so that we can finally see the particle effect 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: @" Particle s_fire.png " ] Cgimage];
[Fire setname: @" Fire " ];

// Add the cell to the layer and we're re done
Fireemitter. emittercells = [nsarray arraywithobject: Fire];

We have generated a cell instance and set some attributes. Set the attributes of emittercells in caemitterlayer-An nsarray array containing cells. Now emittercell has been set, and caemitterlayer is ready to emit particles!

We have set a lot of caemittercell attributes just now. Let's go over them one by one.

    • Birthrate (Birth Rate): The number of particles emitted per second. A good flame or waterfall requires at least several hundred particles, so we set it to 200.
    • Lifetime): A particle disappears after several seconds. We set it to 3.0.
    • Liftetimerange (lifecycle change range): You can use this to change the lifetime of a particle. The particle system randomly takes a lifetime (lifetime-lifetimerange, lifetime + lifetimerange) in this range. In our program, the particle will survive 2.5 ~ 3.5 seconds
    • Color): The color of the particle content. Here we select orange.
    • CONTENTS (content): Used for cell content, generally a cgimage. We assign it to the particle image.
    • Name): You can give your cell a name to search for and modify its attributes in the future.

Run the program to test our particle effect!

 

Okay, it works, but it's not as cool as we think. You can even admit it without disguise that it looks like an orange spot.

Let's make some small changes to make the particles more dynamic. Add the code to the front of setname: on the cell

Fire. velocity =10;
Fire. velocityrange =20;
Fire. emissionrange = m_pi_2;
    • Velocity (speed): Number of records that the particles move per second. Here we move the particles emitted by the cell to the right of the screen. Here we set the following new attributes in caeimttercell:
    • Velocityrange (speed range): Speed change range, similar to lifetimerange
    • Emissionrange (emission angle): This is the angle range of cell emission (in radians). m_pi_2 (PI/2) is 45 degrees (that is, the generated range will be +-45 degrees)

(Compile and run) Check our results

 

This time it looks better, not far from our goal! If you want to better understand how these attributes affect the particle generator, let's make full use of them and modify the attribute values to see the effect.

Add two more lines to end cell settings.

 
Fire. scalespeed =0.3;
Fire. Spin =0.5;
    • Scalespeed (larger speed): The percentage of the Modified Particle size per second. We set 0.3 to make the particle grow over time. Here we set the following new attributes in caeimttercell:
    • Spin (rotation ):The rotation rate of each particle. We set 0.5 to give the particle a nice rotation.

Run again:

 

It looks a bit rusty now. Why? Caemittercell has many attributes to adjust, and the sky type is limited here. Add this sentence after setting fireemitter. emittersize

 
Fireemitter. rendermode = kcaemitterlayeradditive;

This line of code is used to turn our rust smoke into a boiling fireball and run it to check the effect.

What happened? Additive render mode basically tells the system not to use a normal method-a method that covers a drawing particle, but rather a cool method: if the particles overlap with each other, their color intensity will increase! Therefore, you will see a large number of white bright spots in the area of the particle generator, but outside the area is a fireball, where the number of particles decreases due to the continuous extinction, and the color gradient to the original rust. Great!

You may think that the flame is not real now. Indeed, you can modify cell attributes to make the flame effect better. But we need such a thick effect, because we need to plot it. When you drag your finger on the screen of the device, the screen will receive a relatively small number of touch points, so we use a heavy fireball to compensate him.

 

Have fun!


Now, you can finally play with fire (in real life we are told never to play with fire):]

The following is how to draw a flame with your fingers on the screen. We need to modify the position of the particle generator through the user's touch points.

First, declare a method in dwfparticipant view. h:

 
-(Void) Setemitterpositionfromtouch: (uitouch *) T;

Then implement it in dwfparticipant view. M.

-(Void) Setemitterpositionfromtouch: (uitouch *) T
{
//Change the emitter's position
Fireemitter. emitterposition = [t locationinview: Self];
}

 

This method obtains a touch point and acts as a real parameter. It transfers the touch point information to the coordinate system of the particle view and modifies the coordinates of the particle generator.

We need to control it in View Controller, so our next step is to define the interface in viewcontroller

 
# Import <uikit/uikit. h>
# Import"Dwfparticipant leview. h"

@ Interface dwfviewcontroller: uiviewcontroller
{
Iboutlet dwfparticipant leview * fireview;
}
@ End

Then open dwfviewcontroller. XIB then press and hold control to drag the file's owner to the root view. In the displayed tab, select fireview. As you can see, We imported our custom View class, instance variables are defined in dwfparticipant view.

 

Now we can access the emitter layer through View Controller. Open dwfviewcontroller. m to delete all automatically generated code and add the following code:

 
-(Void) Touchesmoved :( nsset *) touches withevent :( uievent *)Event{
[Fireview setemitterpositionfromtouch: [touches anyobject];
}

Try to drag it at a faster or slower speed to see the impact on the particle. Touch and drag it around and you will see the particle generator moving along and leaving a cool flame.

 

Dynamic ModificationCell

The last topic today is to change the cell dynamically at the emitter layer. Now, particle generators have been generating particles. They failed to give users the feeling they painted. Let's change the condition for particle occurrence to generating particles only when the fingers touch the screen. so do not generate it at the beginning, so we will dwfparticipant view. the birthrate of the particle in the awakefromnib method of M is set to 0.

 
Fire. birthrate =0;

If you are running it now, you will find that the screen is blank and good! Next, we will add a method to act as the switch of the particle generator (TRANSMITTER. First, define the following method in the header file of dwfparticipant View:

 
-(Void) Setisemitting :( bool) isemitting;

 

Then implement it in dwfparticipant view. M.

-(Void) Setisemitting :( bool) isemitting
{
//Turn on/off the emitting of Particles
[Fireemitter setvalue: [nsnumber numberwithint: isemitting?200:0]
Forkeypath:@"Emittercells. Fire. birthrate"];
}

The setvalue: forkeypath: method is used to change a cell because the cell name is added to the emitter. We use "emittercells. Fire. birthrate" for keypath because birthrate is an attribute of cells called fire in the emittercells array.

Finally, we need to turn on the particle generator switch at the beginning of the touch and turn it off when we lift our fingers. In the dwfviewcontroller

Add the following code

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

Complete and run ~ Observe the effect ~ Remember, you are playing :-)

 

Where to go from here?

Here is all the code for the sample project.

If you like this tutorial, here are more things you can study. You can

    • Experiment with different particle images
    • Go to the official caemittercell document and check all its attributes.
    • Add a function to render the image on the screen and save it to the image.
    • Save the painting process to a video file
    • Add a burning flame behind the text box of all your applications as the background.

 

To communicate with the Forum, click: Portal!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.