You are on page 1of 53

Editors Note

Dear Readers!
We are proud to introduce the July issue of Flash & Flex Developers magazine! This issue covers great deal of interesting topics especially around Actionscript 3.0 which seems to be obligatory for people who create Flash applications. I highly recommend you to have a look at Spritesheets and Blitting in Actionscript 3.0 by Craig Beswetherick, and discover the power blitting can bring to Flash games. Moving on to the Adventures in Actionscript by Huw Collingbourne, it is worth a while to get to know how to build a FAQ browser that could be added to a web site so that visitors can find and display questions and answers. After familiarizing with those two articles, we can move forward to A Gentle Introduction to Dynamic Programming by Giorgio Natili, and see what dynamic programming is all about. I also encourage you to read further articles written by professionals in Flash & Flex and graphics field. I hope that you will find the articles presented in this issue useful and that you will spend some pleasant time reading Flash & Flex Developers magazine. We put a great effort into this magazine collecting the best articles for our readers. We hope you will appreciate the content of Flash & Flex Developers magazine. You are welcome to contact us with your feedback. Enjoy reading! Enjoy reading! Best regards, ukasz Koka

Publisher: Pawe Marciniak Editor in Chief: Ewa Dudzic ewa.dudzic@ffdmag.com Managing Editor:ukasz Koka lukasz.koska@software.com.pl DTP Team: Ireneusz Pogroszewski Art Director: Ireneusz Pogroszewski ireneusz.pogroszewski@software.com.pl Flex/ActionScript 101 Section Editor: Marc Pires marcpiresrj@gmail.com iPhone Development Section Editor: Ryan DAgostino ActionScript in Action Section Editor: Huw Collingbourne Games Section Editor: Chris Hughes Contributing Editors: Csomk Gbor Proofreaders: Betsy Irvine, Patrick French Publisher: Software Press Sp. z o.o. SK ul. Bokserska 1 02-682 Warszawa Poland Worldwide Publishing Software Press Sp. z o.o. SK is looking for partners from all over the World. If you are interested in cooperating with us, please contact us by e-mail: cooperation@software.com.pl Whilst every effort has been made to ensure the high quality of the magazine, the editors make no warranty, express or implied, concerning the results of content usage. All trade marks presented in the magazine were used only for informative purposes. FFD magazine is available on iPad thanks to MONOGRAM Interactive, s.r.o.

All rights to trade marks presented in the magazine are reserved by the companies which own them. Thanks to the most active and helping beta testers: Russell TangChoon, Lee Graham, Jassa Amir Lang, Ed Werzyn, Yann Smith-Kielland, Justus, Csomk Gbor, Kevin Martin, Charles Wong, Ali Raza, Almog Koren, Izcoatl Armando Estanol Fuentes, Lionel Low, Michael J. Iriarte, Paula R. Mould, Rosarin Adulseranee, Sidney de Koning To create graphs and diagrams we used company. program by

Mathematical formulas created by Design Science MathType

Distributing current or past issues of this magazine without permission of the publisher is harmful activity and will result in judicial liability.

ATTENTION!

The techniques described in our articles may only be used in private, local networks. The editors hold no responsibility for misuse of the presented techniques or consequent data loss.

DISCLAIMER!

07/2011 (25)

CONTENTS
InBrief
06 News
BY CSOMK GBOR

34 Actionscript 3.0 Best Practices


BY PASCAL ECHEMANN

Google has just released a new project called Swiffy on their labs site that converts simple Flash animations to HTML5. It makes perfect sense that they have some technology like this when you look at some of the recent Google doodles.

As we commonly say: The simplest ideas work the best. And the event collection concept is probably one of the most simple reusable piece of code ever written in ActionScript.

DYNAMIC PROGRAMMING
BY GIORGIO NATILI

FLASH ANIMATION

8 Spritesheets and Blitting in Actionscript 3.0


BY CRAIG BESWETHERICK

40 A Gentle Introduction to Dynamic Programming


Dynamic programming is a method for solving complex problems by breaking them down (when applicable) into simpler subproblems.

To implement blitting in a game, the artist must first create a single image that contains all the frames used in the animation. This is what is known as the tilesheet.

WEB DESIGN

INTERVIEW
BY FFD TEAM

14 Vector Graphics
BY RYAN SCHORR

48 Interview with Kevin Ruse


Interview withKevin Ruse, the president and senior trainer at Kevin Ruse + Associates Inc.

Vectors are quickly becoming the future of web design, but few people know how to work with them most likely due to the complexity of existing vector graphics editors on the market.

PRODUCT REVIEW
BY GBOR CSOMK

50 Tanida Demo Builder 8


Demo builder is a special screen capture software, which compresses, edits, and adds tags of the captured video, and then exports it as an interactive flash video with lot of options and settings. The most unique feature among screen capture softwares is that you can instantly edit the captured video, and highlight the important information

MOBILE DEVELOPMENT
BY FOLKO LANGNER

18 Accelerometer Programming
It is worth noting that iOS and Android behave a bit differently. The accelerometer values are read exactly vice versa. Negative and positive values are swapped. The above code in my example is for Apples iOS. For Android, I simply used negative values.

ACTIONSCRIPT IN ACTION
BY HUW COLLINGBOURNE

22 Adventures in ActionScript Putting XML to Work


This month Im going to start a new project. My goal is to build an FAQ browser that could be added to a web site so that visitors can find and display questions and answers. The tool could also be used to create other types of question-and-answer browsers for example, quizzes or tutorials.

FLASH DEVELOPMENT
BY KEVIN RUSE

Sponsors of the Issue


Influxis www.influxis.com ..........................................1, 2, 3 PlugrMan www.PlugrMan.com .......................................... 7 Flash&Math www.flashandmath.com .................................... 11 ActionScriptJobs.org www.actionscriptjobs.com ................................ 13 Streaming Media www.streamingmedia.com/conferences/East2011/ ............................................................................. 17 SapphireSteel Software www.sapphiresteel.com .................................... 21 Kevin Ruse http://www.kevinruse.com/ ................................ 33 Coffee Cup http://www.coffeecup.com/sdrive ..................... 39 FLV Hosting http://flvhosting.com/wp/?p=705 ...................... 47

26 Whats New in Catalyst CS5.5


Flash Catalyst creates interactive applications, but that is just a small piece of the puzzle. However, it is a distinct role and web developers may benefit from having dedicated software to fill that role. Thats what Adobe was banking on with its creation of Flash Catalyst.

07/2011 (25)

IN BRIEF

Flash Builder 4.5.1 with Improved iOS Support

Zombie Tycoon is available in the Sony PSP Mini

Adobe released an update to Flash Builder 4.5 that brings with it improved support for AIR mobile development. It now allows you to create Android, iOS, and Blackberry Playbook applications without resorting to command-line hi-jinx. Launch Flash Builder 4.5 and choose Check for Flash Builder updates from the Help menu. There are actually two updates you will need: the Flash Builders, and the AIR for iOS support.

Altough the Molehill API is still in the incubator phase, the most popular game using it is already up and running on the Sony PlayStation Portable Minis. It suggests that Molehill will soon get in to the Beta builds of Flash Player, and soon to be released.

WebGL will not be publicly available in iOS 5

According to an apple workers letter in WebGL public mailing lists thread (http://www.khronos.org/webgl/publicmailing-list/archives/1106/msg00036.html), WebGL for iOS will only be available for iAd developers. source: The Flash Blog

BlackBerry PlayBook 500,000 units shipped

The most Flash-loving tablet, the PlayBook shipped half million units in 3 months, and willing to sell 3 million by

So it is slightly confusing at first when it comes to the improved iOS support. The Flex 4.5.1 SDK that ships with this update includes the AIR 2.6 SDK. That means you can only use the APIs from 2.6 when creating your applications. But when you compile your iOS applications it is using the updated version of the packager so you will get the same performance as in AIR 2.7. So get this update, compile your iOS applications, and you will get all of the performance improvements. source: The Flash Blog

Adobe AIR 2.7 is Now Available!

the end of the year. The tablet currently runs Adobe AIR 2.7, and Flash Player 10.2, and the Android emulator is on its way. This tablets success is the success of the Flash Platform, and the Flex developers, who have developed tons of apps using the Flex SDK. source: CrackBerry

Adobe AIR 2.7 is now available for everyone to use on most of the platforms, including desktop versions, the BlackBerry Playbook, and Android, but youll have to wait for the iOS packager.

Google has just released a new project called Swiffy on their labs site that converts simple Flash animations to HTML5. It makes perfect sense that they have some technology like this when you look at some of the recent Google doodles. The concept here is similar to the Wallaby technology we released on labs a while back. This is more good news for Flash developers who are looking to target iOS devices that do not support Flash in the browser. source: The Flash Blog

Google Swiffy Converts Flash to HTML5

News selected by Gbor Csomk

07/2011 (25)

FLASH ANIMATION

Spritesheets and Blitting


in Actionscript 3.0
When people started making arcade games, back in the 1970s, they faced many problems due to restrictions forced upon them by the hardware they were using at the time.

What you will learn


How to create a Tilesheet and some tricks to make it easier. How to cache the tilesheet to memory and extract each frame. How to display the tilesheet as a uid animation on the stage.

What you should know


Familiar with the rectangle class. Some experience working with Bitmaps or BitmapData. Familiar with the displayList.

ack of computing power made developers engineer highly optimized systems for displaying graphics to the end user. Blitting is a term used by game developers to describe the process of displaying cached images to the screen from memory, usually from an image known commonly as a spritesheet. Iain Lobb, a prominent Flash game developer previously did some experiments he labeled as the Bunny Benchmark which demonstrates the power blitting can bring to Flash games. The results show the massive improvements that can be made by using a blitting system over using the native display list in the Flash Player. These are the results: The display list demo could render 4000 bunnies at 30 fps on my PC without slowing down. This was replicated by readers on all Mac and Windows browsers except for Mac Safari, where it was down to 10-20 fps. Based on this interesting blog post from Tinic Uro (suggested by Richard Leggett), this seems like it may have something to do with the recent adoption of the Core Animation APIs in Safari. The demos have a lot more layers stacked up than you would need for most games, so this performance drop is unlikely to affect a real game although I will be following up with a new benchmark to test that hypothesis. Bitmaps faired very badly on Android it couldnt even render 10 bunnies at 30fps.

The blitting demo could render 6000 bunnies at 30 fps without slowing down on my PC, and people with faster machines have reported up to 11000 bunnies at 30 fps. Blitting was also much more effective on Android, where it got up to 600 bunnies at 30 fps, certainly enough performance for an arcade-style game. (Thanks to Philippe Elsass for the Android tests).

Someone once argued with me that this might be good for a platform game, but would be terrible for an Asteroids type of game. So I created this set of tutorials to prove them wrong. I then improved performance further with an experimental game timer loop.

If that wasnt enough to convince you that it is the best option, heres a quote from the great guys over at 8bitRocket that also provide some useful extra reading:

Figure 1. It makes life a lot easier if frames for a sprite all t within the same bounding box. Art kindly supplied by @ArtJimp from the game Zomgies 2

07/2011 (25)

Spritesheets and Blitting in Actionscript 3.0

Listing 1a. BlittingEngine.as


package

onName:String, spritesheet:

//imports
import flash.display.Bitmap; import flash.geom.Point; import flash.display.BitmapData; import flash.geom.Rectangle;

BitmapData, numCol:int, numRow: int, colSize:int, rowSize:int, numTiles:int ):void

//create an array to hold the frames that we are blitting


var a:Array = [];

import flash.utils.Dictionary;

//create class {
public final class BlittingEngine

//create a rectangle to use to copy the bitmapData. Set its x and y to 0, //then set the height and width to match the dimensions of the tiles in the tilesheet.
var sourceRect:Rectangle = new Rectan

//create a dictionary variable to hold the blitted animations.


private var _animationList:Dictionary = new

Dictionary();

//constructor { } /** * * This function stores images from a sprite sheet bitmapData object to a Dictionary. * * @param animationName the name of the animation * @param spritesheet The tilesheet bitmapData you want to blit. * @param numCol the number of columns in the spritesheet * @param numRow the number of rows in the sprite sheet * @param colSize the column size in pixels * @param rowSize the row size in pixels * @param startRow the row you want to start on. * @param startCol the col you want to start on. * @param numTiles the number of tiles you need to blit. * @return array of blitted frames * */
public function blitSpritesheet(animati public function BlittingEngine(

gle(0,0,colSize,rowSize);

)
var y:int = 0;

//reset x + y values.
var x:int = 0;

// init class

//create a variable to hold the current number of tiles blitted.


var c:int = 0;

//create vars for the loop. This is quicker than doing it inside it.
var i:int,

j:int;

//for every row {


for(i = 0; i < numRow; i ++)

// for every column in that row j++)


for(j = 0; j < numCol;

//create a new bitmap


var bmpData:

the same size as a tile BitmapData = new BitmapData(

colSize,rowSize, true );

//copy the pixels from the spritesheet, using the rectangle to postion the copyPixels operation spritesheet, sourceRect,new bmpData.copyPixels(

07/2011 (25)

FLASH ANIMATION

Here, I show you how you can build a simple blitting system that will allow you to display an animation on the screen from a tilesheet. I will show you how to create the tilesheet, and then embed this into your Flash. Then I will show you how to cache the animation in code, and finally display it onto the screen. To implement blitting in a game, the artist must first create a single image that contains all the frames used in the animation. This is what is known as the tilesheet. Tilesheets are normally designed in a grid system like the image below, with consistent width and height sizes for each tile. Computers are able to calculate even numbers a lot faster than odd ones, so it helps to make your width and height dimensions multiples of two for tiles in the tilesheet (Figure 1). Creating Tilesheets is a common process for game development and there are a few tools out there that you can take advantage of to help you create them. For those that have created their animations in Flash, you will find SWFSheet by Flash Guru Keith Peters very useful. It is an Air App that produces tilesheets from animations in SWFs so you can make tilesheets from existing artwork very easily. For others that are used to animating in Photoshop, there is a plugin available that is quite useful. The guys over at retroaffect.com released the RA Animation
Listing 1b. BlittingEngine.as
Point(0,0)); //store the animation frame in the array; a.push( bmpData ); //increase the column; x += colSize; //update the rectangles position sourceRect.x = x; //increase the blitted tiles counter c ++; //if the current tile is the last tile, break out of the loop and stop blitting images. {
if(c == numTiles) break;

Exporter to make the process of creating tilesheets from Photoshop animations as easy as possible. I advise you give it a try if you are planning to create a tilesheet from a Photoshop animation. Blitting improves speed by storing graphics in cached memory and then duplicating items to the screen. When using MovieClips in Flash the vector engine uses a lot of mathematics to redraw every line, which is costly to the CPU. Therefore, when you have a lot of them on the stage at once, the processor quickly becomes bogged down with the cost of calculating and rendering each individual vector cycle. Even though the rendering engine in Flash Player does recognize redraw regions and focuses on those, blitting allows more control over the rendering process and provides much more speed. This, in turn, enables developers to push the boundaries of their applications much further. With blitting, each frame of the animation is prerendered and stored in memory. When the sprite graphic needs to change from the current one, the corresponding cached image is retrieved and displayed. This reduces the time that it takes to render each vector graphic and by taking advantage of this technique game developers can greatly improve the amount of graphics displayed on the screen at any time and frame rates will improve.

//increase the positon by 1 tile y += rowSize; //update the source rectangles new position sourceRect.y = y; //reset the column back to the left x = 0; } sourceRect.x = x;

//store the blitted animation in the Dictionairy for use later } animationList[animationName] = a;

//create the getter for the animationList variable.


public function get animationList():Dictionary

} }}

return _animationList;

10

07/2011 (25)

Spritesheets and Blitting in Actionscript 3.0

Listing 2a. BlittingEngineTest_Example.as


package

//remove the old listener


this.removeEventListener(Event.ADDED

//imports
import flash.display.Bitmap; import flash.display.Sprite; import flash.events.Event; import flash.geom.Point; import flash.display.BitmapData;

_TO_STAGE, init);

//create a new blittingEngine


var blitEngine:BlittingEngine = new

import flash.events.MouseEvent; import flash.geom.Rectangle;

BlittingEngine()

//create a spritesheet from the one in the library.


var testSpriteSheet:BitmapData = new

//use this to set the SWF width, height, framerate and background color [SWF(width="800", height="600", frameRate="24", backgroundColor="#FFFFFF")]

Tilesheet_PNG(2048,2048);

//pass the spritesheet to the bliting engine. blitEngine.blitSpritesheet("testSpr TILE_WIDTH,TILE_HEIGHT,10 ); itesheet", testSpriteSheet,2, 5,

public class BlittingEngineTest extends Sprite public function BlittingEngineTest()

//get the animation from the blitEngine. animation = blitEngine.animationList ["testSpritesheet"];

//test the engine test runBlitToScreenTest();

} //

******************** testing *********************** *****

//if you like, trace out the number of frames to make sure you have the correct amount. trace( "ANIMATION FRAME COUNT = ", animation.length );

//create some varaibles to hold the tile width and height.


private static const TILE_WIDTH:int = 256,

//create a bitmapData for the displayed test animation; testBitmapData = new BitmapData( TILE_WIDTH,TILE_HEIGHT, true);

int = 256;

TILE_HEIGHT:

//create some variables to animate the blitted tilesheet


private var testBitmap:Bitmap,

//create the test bitmap testBitmap = new Bitmap( testBitmapData );

testBitmapData:BitmapData, animationCtr:int,

animation:Array = [];
private function runBlitToScreenTest():void

//add the test bitmap to the display addChild( testBitmap ); //position the bitmap testBitmap.y = 100; //add the mouse listener stage.addEventListener( } MouseEvent.CLICK, onClick);

//add a added to stage listener to fire when the stage is availible.


this.addEventListener(Event.ADDED_TO_

STAGE, init);

private function init(e:Event):void

07/2011 (25)

11

FLASH ANIMATION

Listing 2b. BlittingEngineTest_Example.as


private function loop(e:Event):void

//remove the loop listener Event.ENTER_FRAME, loop); //add the mouse listener MouseEvent.CLICK, onClick); } addEventListener( removeEventListener(

///every frame.... //increase the frame counter animationCtr += 1; //get the correct frame from the chached animation in the library
var frame:BitmapData = animation[

animationCtr ];

//copy the animation from the library to the test bitmap testBitmap.bitmapData.copyPixels( frame, new Rectangle(0,0,TILE_WIDTH,TILE_HEIGHT),new Point(0,0)); //check to see if we are at the last frame of the animation
if( animationCtr == animation.length -1 )

private function onClick(e:MouseEvent):void

//add the loop listener addEventListener( Event.ENTER_FRAME, loop, false,0,true);

//remove the mouse listener removeEventListener( } }//end class MouseEvent.CLICK, onClick);

//reset the counter if we are animationCtr = 0;

}//end package

The code required to actually Blit a tilesheet to memory is quite simple. We know the dimensions of each row and column in the grid and we can use this information to cut out each frame. We first create a rectangle in code with the same dimensions as each frame. We then create a loop that iterates over the tilesheet and moves the rectangle based upon the row and column size of the grid. We use the rectangle area to take a snapshot image of the tilesheet, using its x, y, width and height values as the reference point for copyPixel operations. As we move the rectangle, we capture each frame of the animation, and store them into an array for later use. Because we want this to be as reusable as possible, lets create a class to contain this functionality making it easy to drop into other projects. Here is the code for the BlittingEngine.as class: see Listing 1. We have just created a reusable class to manage blitting tilesheets and store them in your projects. It is able to read a spritesheet image as BitmapData and then cut out each frame in the animation based upon information passed to the method. Consider once more the animation in the demo spritesheet. As you can see, the final tile is blank. This is a common issue with tilesheets, which can cause a blank tile in the animation. A simple solution we have implemented here is to set the total number of tiles we

need to cut out and to stop reading them once we get to that value. This is not the most ideal solution, and we will address this in a later tutorial. We now need a test for the Blit Engine. Create a new class called RunBlitToScreenTest.as. We will use this to test the blitting engine class, BlitEngine.as. This class is merely used as a demonstration of the engine, and the blitting engine does not depend on the class to function properly (Listing 2). If you run the above code, you should see the tilesheet animating on the screen. Flash users will want to set RunBlitTestAnimation.as as their document class, Flash/Flex Builder users will want to set this class as their default application file for this project. This is a very basic example of blitting, to use this in a real project, you would want to extend this functionality a lot further. In the next article, we do this by adding a background image and applying blitting to multiple animated sprites.

CRAIG BESWETHERICK
Craig Beswetherick is a casual games developer from Cornwall, UK. Currently based in London, Craig works for Substance during the day creating games for the lm industry and by night he works on his own indie games projects under the name Grindhead Games. Follow Craig on twitter - @grindheadgames

12

07/2011 (25)

WEB DESIGN

Vector Graphics
Are the Future of Web Design But Nobodys Using Them Yet
A little while back, the developers at the company I work for, CoffeeCup Software, had an epiphany: Vectors are quickly becoming the future of web design, but few people know how to work with them most likely due to the complexity of existing vector graphics editors on the market.
What you will learn
How vectors are changing web design Why vectors are easy to customize How to use Web Image Studio Lite

What you should know


Basic web design Basics of image editing software General understanding of modern browsers

his is unfortunate, considering how useful they are by comparison to the images we all see on the web every day. If youre not sure about the difference, lets look at a little bit of history.

A Brief History of Vectors

If youre familiar with Flash, you already understand the power of vectors. Because theyre a a set of instructions rather than a grid of colors, theyre efficient in file size, scale flawlessly, and can be used to create elegant curves and other shapes easily. If you dont think youre familiar with vector graphics, youve at least seen them before. Theyre in just about every Flash animation youve ever seen, from games to banner ads. You can recognize them by their smooth and consistent styling. By comparison, most images you see on the Internet are raster graphics (more commonly referred to as bitmaps) such as JPGs, GIFs, and PNGs. Theres a huge difference between bitmaps and vector graphics. First, the information in bitmaps is absolute and composed of pixels. Unfortunately, this means that their resolution cant really be increased once theyre created, because increasing their size will exaggerate their pixels. By comparison, vector graphics can be scaled to any size without a loss in quality. Most bitmaps use advanced compression techniques to reduce file size. Raw, uncompressed bitmaps tend to be huge, since they can contain literally millions of dots that each have their own color information.

Vector graphics are composed of paths and color information, so their file sizes are often but not always significantly smaller while at maximum quality. As a result, the dimensions of a vector graphic rarely have much of an impact on its file size. Though vector graphics existed as far back as the 1960s and have been in constant use since then, a rapid increase in video adapter technology led to widespread adoption of the more photo-realistic raster graphics that are used across the web today. However, with the development of Flash, vector graphics began to make a comeback. Flash was the first major method for vector graphics to be implemented on a webpage, and the technology even went a step further and added animation and interactivity to the format. The only major weakness of the use of Flash on a webpage is that each visitor must have the Flash plug-in installed for the browser theyre currently using in order to see the content. However, as vectors are making their great comeback, browser developers have begun to support

Figure 1. Vector vs. raster graphics

14

07/2011 (25)

Vector Graphics are the Future of Web Design But Nobodys Using Them Yet

their use so that web designers can utilize them to build webpages that scale flawlessly. Fluid web design is a trend rapidly growing in popularity, and is a likely future for the web. Since text already scales flawlessly being a vector format itself and many web designers use percentages and relative measurements to create a pages layout, many websites can be stretched to any dimension or zoomed to any level without a noticeable loss of quality; the only portion of the webpage that is not fluid are the raster graphics. The most common vector graphic format in use today is the Scalable Vector Graphics format, or SVG. This format is generally used for icons, fonts, and even large images. This file type, like other vector formats, is composed of instructions that tell a program how to draw the image. In fact, you can open any SVG file with a text editor and look at the instructions its basically an XML file. Because all major browsers already support XML, this makes supporting SVG a fairly simple task; however, no major browsers currently support SVG entirely. This makes the use of vector graphics on the web a delicate and possibly unstable choice without using Flash. Therefore, Flash tends to be the best option for using vector graphics on a webpage. The limitation in this case is that the Flash content generally cant be interspersed with any non-Flash content, so most designers tend to rely on bitmaps exclusively if they want a non-Flash webpage. However, this doesnt mean that vectors are irrelevant in modern web design!

looking a little weird. In either case, scaling a bitmap reduces quality. As an alternative, because vector graphics scale flawlessly, a 150x150 pixel vector graphic can be increased or decreased to any desired size and exported without sacrificing quality one bit. Therefore, if the source file of the webpages graphics are in a vector format, the graphics being used can fit any dimensions required by the web design while still maintaining maximum quality.

Customizing Vector Graphics

Using Vectors to Create a Perfectly Scaled Web Graphic

Vector graphics can carry a lot of detail without being too bulky, which is one of the things that makes them an attractive alternative to raster graphics. They also work well on webpages where their smooth lines and gradients can look slick and modern. The problem is that these vector graphics cant be safely used on a webpage; they must be converted into a raster graphic first. Nearly all vector graphics editors feature exporting options which allow you to take either an SVG or some other native format and save it as another format, which means that you can convert your SVGs to PNG, JPG, GIF, and other popular and universally-supported formats. When done properly, these converted images can look almost identical to the source vector image. This is a superior method when it comes to scaling. For example, lets say that weve got a 150x150 pixel JPG that we intend to use on a webpage, but we need it to fit into a 200x200 pixel space. Increasing the dimensions of the JPG manually within the HTML code or with an image editor would leave the graphic looking fuzzy and low-quality. Most raster images can be scaled down to the proper size without a drastic reduction in quality, but even in this case the image can end up

If the graphic that is intended to be used is a photograph or other realistic image, a photo editor is the best option for making customizations. These modifications are generally limited to cropping, altering color balance, and touching-up blemishes in the image. However, if the graphic that will be used is composed of vectors, the possibilities are endless. Every component of that graphic is editable, so shapes can be changed, colors can be swapped, and entire groups of elements can be moved all at once. Customizing vector graphics might be even more useful than scaling them. Because you have complete control over every aspect of that graphic, you can change it into exactly the image you need. For example, elements of that graphic that are hidden behind other elements can be brought into view simply by moving the object out from behind the other one. By comparison, selectively changing colors in a raster image is very complicated and difficult, and moving elements of images can be impossible because in many cases, like when using a flattened (non-layered) image, the information doesnt even exist. There are several widely-used vector graphics editors that can make precisely these customizations. Unfortunately, these programs tend to be so overly complicated that the user must invest countless hours learning them in order to be able to use them. Tasks as seemingly simple as applying a gradient to a shape can become all-day training sessions. Unfortunately, that seems to be the way that things are in the math-heavy vector world. But wait a minute! What about Flash? As it turns out, Flash is an efficient platform upon which relatively uncomplicated user-friendly applications can be created. Because Flash helps bring the power of vectors to the average web developer, it can be used as the basis of

Figure 2. Moving objects in a vector graphic le

07/2011 (25)

15

WEB DESIGN

a vector graphics editor that anyone can use. And thats exactly what we did at CoffeeCup.

Figure 3. An overview of Web Image Studio Lite

Using Web Image Studio Lite to Customize Web Graphics

Web Image Studio Lite is our answer to those overly complicated, too-many-features-having graphics programs. It gives you all the power to customize graphics as necessary in an interface that feels familiar and simple. Those tasks that would take massive amounts of knowledge and effort in other vector graphics editors are simplified in a way that retains the power of a pro-level editor while being manageable for the average web developer. In an age where more people are creating content for the web than ever before, there is a higher demand for simplified tools to assist those who dont have the time to read a 300-page manual. But even for those that are familiar with advanced design tools, a less cluttered tool can be a big help. Web Image Studio Lite is the program intended to meet this demand. The program has cut out a lot of the clutter that youd find in a $500 vector graphics editor but preserved all the tools you need to make quick, easy customizations to your web graphics. There are line, shape, text, and image creation tools, and theres a set of tools used for arrangement and layer management. The interface is so uncomplicated that users tend to become fluent with the program from just a few minutes of messing around with it. Probably one of the most useful components of the program is the Color Palette tab, where every color that is currently being displayed within the project is shown. This allows the user to see which colors are being used at a glance, but it also provides for quick changes to the

color scheme of the object being edited. For example, in a vector graphic of a red apple, the user would just need to replace each shade of red with analogous shades of green to recolor the object. Theres no eyedropper, magic wand selection tool, or fill/gradient tools necessary to make this change. One of the more interesting parts of Web Image Studio Lite is the Effects tab which features a fill tool that allows linear and radial gradients, a stroke tool to adjust the attributes of lines, and a shadow tool for creating quick, professional-looking drop shadows beneath objects. The registered version has even more effects, including blur, glow, reflection, and bevel tools. Once the graphic has been exported as a raster image, it can be can be tweaked even further directly within the program. The Picture Editor tab has a set of tools including brightness, contrast, saturation, and hue controls. Web Image Studio Lite has pretty much everything a web designer needs to work with vectors thanks to some clever C++ programming and Flash as its main drawing engine. It builds upon decades of vector technology yet brings it down to a level where anyone can use it. Sure, vectors might be the future of web design, but that doesnt mean they have to exclude anyone.

Figure 5. The effects tab

Conclusion:

Be on the lookout for more widespread use of vector graphics on the web in the next couple years. The dimensions of browsers and the devices they run on are never going to be uniform, and so it is important that future web designs scale as smoothly as possible. From tablets and cell phones which display websites in portrait or landscape mode, depending on the users orientation to laptops, PCs, and TVs, browsers come in all shapes and sizes. When they all fully support vector formats, well use them in our designs; but for now, well just need to use them to create high-quality raster images.

RYAN SCHORR
Figure 4. Changing colors in Web Image Studio Lite

Ryan Schorr is the creative and technical writer for CoffeeCup Software: http://www.coffeecup.com/ and can be contacted at rschorr@coffeecup.com

16

07/2011 (25)

ACCELEROMETER PROGRAMMING

Accelerometer Programming
What you will learn
How to program the accelerometer sensor to realize inclination measurement (bubble level). About minor differences in accelerometer scripting and major differences concerning faster GPU iOS rendering and Androids Force Stop enabling the app to be moved to the external SDcard memory

Smiley 4 U fla Source for iOS & Android Included


For a flash coder the world of smartphones is kind of new. So, there is a lot to discover.
What you should know
AS3 action-script skills How to publish an iPhone app in Flash CS5 How to publish an Android app in Flash CS5 up

fter watching the smoothly rotating compass needle in Apples iPhone ads over and over again and reading about the deviceOrientation and StageOrientationEvent in the Flash CS5 AS3 reference manual, an idea struck my mind out of the blue. I wanted to realize a stage rotating smoothly 360 depending on the position of the device. Certainly the StageOrientation commands would be useful. I anticipated a simple solution that was like 5 minutes away. Well, I was dead wrong. The stage orientation is returning ROTATED_RIGHT ROTATED_LEFT even UPSIDE_DOWN and one can execute code depending on those events to align the cast members on the stage anew. This event is good for apps tailored to display different content in landscape and portrait mode but to no avail for my 360 rotation task. I thought I was very close and the rotation of the device could be accomplished. Of course the previously mentioned compass was most likely realized by means of the Geolocation constructor and of no use for this endeavor. Next, I browsed around in iTunes and quickly found bubble levels and tools for inclination measurements in degree. Thats basically exactly what I intended to realize in flash. So, I kept pondering my idea and logically the right approach to resolve this problem was the accelerometer. I had tested the respective code snippet provided by Adobe which can be found in the reference manual. It demonstrates moving a ball across the stage depending on the movement and position of the

device. Yes, Im talking about the official accelerometer and motion sensor example. OK, one gets to read accelerationX Y even Z as positive and negative values roughly ranging from -1 to 1 as float. Sounds nice, but would this actually work out for a rotation measured in degrees? The first thing I did to find clues was compiling an app which outputs these XYZ accelerometer values in a simple textfield as string. I quickly realized that the Z

18

07/2011 (25)

Accelerometer Programming Smiley 4 U fla Source for iOS & Android included

axis is not the motion I was looking for. Yet the XY accelerometer values constantly kept changing while rotating the device in my hand. These values were somewhat confusing though. So I grabbed a sheet of paper and drew a cross-hair resembling a compass. To clarify the matter I tilted the device and wrote down the values. I tilted to the left and wrote down the xy values in the left top of the cross-hair tilted to -90 or 270 to the right and upside down and so on. After examining those numbers, I was still a bit confused after examining those numbers. So my second thought was how to put this all in actionscript code. If x is greater than 0 and y values are negative ... well this riddle kept me busy all afternoon long to tell you the truth, yet programming it was much fun as I appreciate a little challenge. The try and error method worked out fine here, as it often does. For visual testing purposes, I drew a round smiley face :-) on Flashs stage. The expected result should be a smiley, you guessed it right, which stays upright no matter how much and in which direction one rotates the device. The smileys registration point was in the center of course as preparation for the rotation. The smileys movieClip itself as well was placed in the center of the stage. Due to the fact that the read data kept changing from -1 to 1 when rotating the device, multiplying the accelerometer values by 90 made alot of sense to come up with the desired degree values. The variables xSpeed and ySpeed increase or decrease with the motion of the accelerometer sensor as said.
xSpeed = e.accelerationX*90; ySpeed = e.accelerationY*90;

ran into minor problems with degree numbers greater than 360 or negative rotation values, so I had to add a few more if statements to achieve smooth results and to keep the values in range while rotating the device from lets say -180 to 180 degrees upside down and back and over and over again. But that was not much of a feat. However, after a few hours had passed, I had a fine working result. Compiling ipa for iOS takes quite a lot of time. Developing for Android is way faster thanks to that launch on device option but that wasnt available as I developed this script. Anyway amazingly, I had the rotation I was looking for. So, at some point, I was troubled by thoughts that flash wasnt good for this; I got to admit. I felt relieved! :-) It literally turned out perfect. Wow! After code optimization, I had reduced all statements to just a few lines to get the logic right. Lets take a closer look at these few lines representing the rotation in degree calculation:
if(ySpeed<0){

myRotation=-xSpeed

}else if (xSpeed<0){ }else { }

myRotation=90+ySpeed; myRotation=-180+xSpeed;

These few lines are actually interlaced inside an ENTER _ FRAME loop and do take those accelerometer values into consideration.

It is worth noting that iOS and Android behave a bit differently. The accelerometer values are read exactly vice versa. Negative and positive values are swapped. The above code in my example is for Apples iOS. For Android, I simply used negative values. No further adjustments were required:
xSpeed = -e.accelerationX*90; ySpeed = -e.accelerationY*90

Then, I had to write an algorithm as if x is upside down or negative then take y into consideration and so on. I

Figure 1. Android system, Manage Apps settings

07/2011 (25)

19

ACCELEROMETER PROGRAMMING

Id like to mention a few more platform specifics since we found differences between accelerometer sensor scripting for iOS and Android. The most striking difference is that iOS is supported by Air 2.0 shipped with Flash CS5 and Android is officially supported since the release of CS5.5 which includes Air 2.5. Im not going to talk much about all the development and distribution certificates and provisioning files required by iOS to compile and test your flash app on a device nor about installing Java and other preparations for the Android workflow. Im just going to stick to explaining some as3 coding methods. In iOS, these next 3 lines enable fast GPU rendering, see>iPhones Settings ...>General
var iSmilyMx:Matrix = new Matrix(); iSmily.cacheAsBitmap=true;

shut down automatically after the user specified time elapses.


NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;

Move to SD Card support available since Android 2.2 is essential to save much limited internal phone memory. After compiling, Flash generates an xml application description file with all the permissions etc. in the same directory as the apk file. With any text editor you can change this line:
<![CDATA[<manifest> alter that line to: <![CDATA[<manifest android:installLocation=preferExter nal>

iSmily.cacheAsBitmapMatrix = iSmilyMx;

Apply a cacheAsBitmapMatrix by means of these 3 lines to an object added to the stage. Here the object represents the smiley graphic, which is called iSmile. This makes a huge difference in rendering performance. You should test an animation adding bitmaps or vectors and breaking bitmaps apart without these lines to find out about this effect. One can add multiple objects to the same bitmap matrix but to my knowledge, it is restricted to 1000x1000 pixels. So adding only animated objects makes sense. For the Android system, the Manage Apps settings are of great interest, see Figure 1. The NativeApplication class of Air can be used to Force Stop (see red arrow in Figure 1) to exit the app. Doing so might not be desired in any case though. Yet it can help to conserve battery consumption. The difference is most noticeable if multi-tasking or restarting the app. The app will start from the beginning if force stop mode was added otherwise the last screen before hitting Androids Home or Back button to exit the app will show. Using the Back button to return to your app will be disabled once you quit or deactivate having Force Stopping on, for example, if calling an email client from within your app.
NativeApplication.nativeApplication.addEventListener (Event.DEACTIVATE,applicationDeactivate); function applicationDeactivate(event:Event):void { force close the app on Android }

NativeApplication.nativeApplication.exit(); // this does

Simply compile your apk once again, and your app is stored on the SDcard by default and can be moved back to the phone in the Android settings by the user manually (see green arrow in Figure 1). By the way, Apple rejected this Smiley app in an as is condition stating the iOS Developer Program Agreement: The Smiley App does not enhance the user experience of iOS. Tough! So this Smiley 4 U is not available in iTunes. Sorry about that. Anyway, the script might be useful for round buttons or games next to the inclination measurement. Feel free to use it ... just dont upload the same without substantial changes please. I submitted this app to the Android Market Place as toddler entertainment and hope to have motivated mom and dad to go play with their kids in between ... :-) These kids will turn out tech savvy! You can find and install this app by going to https:// market.android.com/details?id=air.SmileAndroid with your browser. There you will also find a special promo video helping your imagination. Also you can install the free smiley app by scanning this QRcode with an android device using the barcode scanner. Thanks, Folko of www.advance-media.com your as3 Flash 3D charts provider.

For apps that do not require user interactions for a longer period of time like video streams, the KEEP _ AWAKE mode needs to be set in the source code as well as in the permissions of Android. Otherwise, the device will

FOLKO LANGNER
Webmaster of www.advance-media.com Mail: info@advance-media.com Author of 3D Charts ash tool Studied computers at the University of Dortmund, Germany

20

07/2011 (25)

ACTIONSCRIPT IN ACTION

Adventures In ActionScript
Putting XML To Work
Huw Collingbourne starts a new project which uses XML to create an online FAQ browser.

What you will learn


How create XML data structures How to save XML to disk How to load XML data from the web

What you should know


Basics of event-handling Creating event listeners Creating custom classes

his month Im going to start a new project. My months, I think it would be more interesting to explore goal is to build an FAQ browser that could be some other possibility. Ive decided to use XML. This added to a web site so that visitors can find and has a number of advantages. First, it gives me the display questions and answers. The tool could also option of editing my data in other XML-capable editors be used to create other types of question-and-answer such as Dreamweaver or Visual Studio; secondly, browsers for example, quizzes or tutorials. being a human readable format, XML makes it easy to There are really two main elements to this project. check that the saved data is correct; and, finally, since First I need to write a program to help create my ActionScript has lots of useful XML processing classes question and answer database. This program will and methods, it should be relatively painless to write the run on my desktop computer. Then I need to write a data-manipulation methods of my application. separate program to allow users to browse through the database and display specific FAQ items. That program will be deployed on my web site. Before starting to do any coding, I first need to decide on a format in which to store data. My database will be pretty simple so I dont need a dedicated database server. I could store data in binary format using the ByteArray class. However, since I used byte arrays in the adventure game project which Ive Figure 1. Ive designed a simple user interface to save and load XML text in XML format. Here I am been writing about in recent using the Amethyst IDE with Flex 4 but the same principles apply to any type of ActionScript program

22

07/2011 (25)

Adventures In ActionScript Putting XML To Work

Listing 1. Using HTTPService


private var _srv : HTTPService; private function doLoadXML( ) : void { _srv = new HTTPService( ); _srv.url = _fr.name; _srv.send( );

_srv.resultFormat = "e4x"; _srv.addEventListener( ResultEvent.RESULT, xmlLoaded ); }

_srv.addEventListener( FaultEvent.FAULT, xmlLoadedFault );

private function xmlLoaded( e : Event ) : void { xmlList = XML( e.result ); _xmlData = XML( e.result );

private function xmlLoadedFault( e : FaultEvent ) : void { var msg : String = e.fault.faultString; } Alert.show( msg, title );

var title : String = e.type + " (" + e.fault.faultCode + ")";

Loading Data From A URL

the IEventDispatcher interface. This defines methods for As the FAQ browser will be deployed in a web page, adding or removing event listeners, checks whether it needs to be able to load data from a URL rather specific types of event listeners are registered, and than from my local file system. There are two ways in dispatches events. Ill explain why this is necessary which I can program this behaviour. Either I can use an shortly. HTTPService object or I can use a URLLoader. Both To use the SaveLoad class to load XML data you these classes are able to make requests for data stored would first need to create a SaveLoad object. In my at a specific address. The address could be either a file code (see the Get The Source Code box for download path or a location on the Internet. It is largely a matter information), Ive done this in the init() method. of preference as to which of these classes you choose This method executes when the application first when working with simple XML. The HTTPService class supports a great variety of data types while the URLLoader class supports more events. Here Ill be using URLLoader. However, if you want to try HTTPService, refer to Listing 1 for a simple example. In previous columns, I wrote a class, SaveLoad, to handle saving and loading of binary data. Ill add additional XML saving and loading capabilities to this class. As before, the Figure 2. You can load an existing XML data le from disk, add more items to the XML structure and SaveLoad class implements then save the modied XML back to disk again as seen here

07/2011 (25)

23

ACTIONSCRIPT IN ACTION

runs because Ive specified the method name as the applicationComplete event-handler in to the Application tag in the MXML of my user interface:
applicationComplete=init()

This is how my init method creates the object:


var sl : SaveLoad; private function init( ) : void { } sl = new SaveLoad( );

In my program, this method simply assigns the loaded XML data to an XML variable named qalist and then displays it in a text area. This is, of course, rather a primitive way of displaying XML and Ill improve upon it next month. For now, however, I have plenty to do just to ensure that the XML data is loaded correctly. The loading itself is done inside the SaveLoad class. Lets now see how this is done. When my code calls sl.loadXML(), this method executes:
public function loadXML( ) : void {

myXMLURL = new URLRequest( C:\\xmltest.xml ); myLoader = new URLLoader( myXMLURL );

Ive defined a Load button which the user clicks in order to load the XML data. This is the buttons click event-handler:
private function loadBtn_click( event :

myLoader.addEventListener(Event.COMPLETE, xmlLoaded );

flash.events.MouseEvent ) : void {

sl.addEventListener( Event.COMPLETE, afterLoadingXML ); } sl.loadXML( );

Notice that it begins by adding an event listener to the SaveLoad object. Then it calls the loadXML() method. Once the XML has completed loading, it dispatches an Event.COMPLETE event (this is why SaveLoad needs to implement IEventDispatcher) and the afterLoadingXML() method executes:
private function afterLoadingXML( e: Event ) : void { qaList = sl.xmlData; XMLTextArea.text = qaList.toString();

The URLRequest and URLLoader objects are declared earlier in the SaveLoad class. The URLRequest object is passed a string path to a URL in its constructor. Here, Ive specified a file on my local disk but you may also specify a Web-type URL such as http://www.example.com/ example.xml. Once the URLRequest object is created I pass it as an argument to the URLLoader constructor. This object provides methods for downloading data. If, as here, a download address is specified in the constructor, the URLLoader object starts downloading data immediately. An event-listener is set to trigger when the data loading has completed. This causes the xmlLoaded() method to run. It is important to wait for the Complete event before trying to access loaded data. If you dont wait, you will probably access an empty or incomplete set of data. This is my xmlLoaded() method:
private function xmlLoaded( e : Event ) : void _dispatcher.dispatchEvent( new Event( Event.COMPLETE ) ); } _xmlData = XML( myLoader.data );

This simply assigns the loaded data (myLoader.data) to an XML variable, _ xmlData. It then dispatches a Complete event. It is this event which is received by the SaveLoad event listener which was added in my buttons Click event-handler (see loadBtn _ click).

Figure 3. Here I am using the Amethyst debugger to break before saving XML data. Amethysts XML Viewer lets me preview the data stored in the XML structure before writing it to disk

Now lets turn to the problem of generating the XML data in the first place. Ultimately, it is my plan to

Creating and Saving XML

24

07/2011 (25)

Adventures In ActionScript Putting XML To Work

Get The Source Code

The archive containing all the source code for this game is available for download from the SapphireSteel Software site at: http://www.sapphiresteel.com/tutorials/amethyst-tutorials/ actionscript-programming/article/faq-browser

First I create a pair of tags to define the list of Question and Answer items:
private var qaList : XML = <QALIST></QALIST>;

use a separate program for this task. I want to create the XML database locally and upload it onto my web site to allow users to search it. But, to keep things simple, this month Ive added some basic XML saving capabilities to the same program that loads the data.
Listing 2. Appending a Question and Answer Item to the XML data
private function addBtn_click( event : {

The user interface has two data entry fields: a TextInput in which a question can be entered and a TextArea in which the answer can be written. When the Add button is clicked the addBtn _ click() method creates a new question and answer (<QA>) item and appends it to the XML data in qaList (see Listing 2). Notice that this inserts the question and answer string variables into pairs of tags by enclosing them between curly brackets:
<QUESTION>{question}</QUESTION> <ANSWER>{answer}</ANSWER>

flash.events.MouseEvent ) : void

var question : String; var answer : String; var qa : XML;

question = QTextInput.text; qa =

answer = AnswerTextArea.text; <QA> <QUESTION>{question}</QUESTION> ANSWER> <ANSWER>{answer}</

When I want to save the data, I call sl.saveXML( qaList ). If youve been following my previous columns, the data-saving method will look familiar as it is similar to the method I use for saving ByteArrays. The only real difference is that this time, the incoming argument is an XML object:
private var _fr : FileReference; public function saveXML( someData : XML ) : void { _fr = new FileReference( ); _fr.save( someData );

</QA>; }

qaList.appendChild( qa );

Listing 3. A sample XML data le


<QALIST> <QA> <QUESTION>What is the capital of France?</ <ANSWER>Paris</ANSWER> QUESTION>

</QA> <QA>

<QUESTION>How many eggs make a dozen?</ <ANSWER>Twelve</ANSWER> QUESTION>

The save() method of the FileReference object causes a disk browsing dialog to appear. The user can then save the data to any location. In my code, data is loaded from C:\\xmltest.xml so thats where the data file should be saved. See Listing 3 for an example of a data file in which three pairs of FAQ questions and answers have been saved. So, that, in essence, provides the foundations for two programs one that can be used locally to create an XML database and another than can be deployed on the web for users to display questions and answers. The next thing I need to do is to create a nice user interface in order to display the data. Ill do that next month.

</QA> <QA>

HUW COLLINGBOURNE
Huw Collingbourne is Director of Technology at SapphireSteel Software. Over more than 20 years, he has programmed in languages ranging from Ruby to C# and has been a technical columnist for computer magazines such as PC Pro and PC Plus. He is the software lead of the Amethyst Designer, the Flex user interface design environment of the Amethyst IDE for Visual Studio. SapphireSteel Software: http:// www.sapphiresteel.com/

<QUESTION>Who killed Laura Palmer?</QUESTION> </QA> <ANSWER>Beats me!</ANSWER>

</QALIST>

07/2011 (25)

25

FLASH DEVELOPMENT

Whats New In Catalyst CS5.5


What is Flash Catalyst and what is it used for? This is a question I get in almost all of the Flex/Flash Builder classes that I teach.

What you will learn


Basic understanding of Rich Internet Applications Basic knowledge of Adobe Flash Builder Basic knowledge of Adobe Flash Catalyst CS5 (optional)

What you should know


What Flash Catalyst is and how it can help you develop Rich Internet Applications Specic new features in Flash Catalyst CS5.5 When to use Flash Catalyst CS5.5

am an Adobe Certified Trainer and while I teach many software packages in the Adobe product line, I have spent the majority of my time in the last year and half teaching Flex/Flash Builder to Java, .NET, C# and HTML/CSS/Javascript developers in top Fortune 500 companies throughout the U.S. and Europe. In this article I will shed some light on Flash Catalyst, the newest product in the Flash Platform. In addition, I will explain some of the new features of Flash Catalyst CS5.5 that have been increasing the interest level in this software. In summary, I will describe what I think are the best use cases for Adobe Flash Catalyst CS5.5.

What is Flash Catalyst?

According to Adobe Catalyst CS5.5 is approachable interaction design software that enables you to easily transform Adobe Photoshop, Illustrator, and Fireworks artwork into expressive, fully interactive projects without writing code, and leverage the reach and consistency of the Adobe Flash Platform. Most of the developers in my workshops have heard this definition and are left wondering will it work in my environment? To answer that question, or at the least, provide some anecdotal evidence that will enable developers to come to a reasonable conclusion on their own, I should provide a brief background and history of Adobe Flash Catalyst. Catalyst was first introduced under the code name Thermo and made its debut for public consumption with

the release of Catalyst CS5 on April 30, 2010. Although packaged with CS5, Catalyst was a 1.0 product at that time. The goal of Flash Catalyst was to generate code to be compatible with Adobe Flex Builder. Adobe Flex was originally called the Macromedia Flex Server 1.0 and was designed for enterprise application development. However, by the time Catalyst (1.0) was released, Macromedia had been acquired by Adobe Systems and had already released Flex Builder 2 and Flex Builder 3 which were software development kits which Adobe based on the open source Eclipse platform. Catalysts release was timed roughly with the release of Adobes new version of Flex Builder which was renamed Flash Builder 4.0. The next and most recent release of Catalyst is version CS5.5 and it includes some very welcome features which will be explored in this article. The grand vision for Flash Catalyst was to bridge the gap that is often present in web application development between the designer and the developer. Catalyst focused on a clear division of responsibility between the roles of graphic designers, interaction designers and developers. In addition, they touted the use of their products and aligned them with the corresponding user roles. For example, the following workflow aligns certain Adobe products with team members and their roles: The graphic designer who may be responsible for the overall look of a web application will typically create dialog boxes, icons, buttons, etc. Many times the graphic designer is responsible for creating the style guide as

26

07/2011 (25)

Whats New In Catalyst CS5.5

well which indicates the proper use and specification of colors, gradients icon sizes and logo placement rules. The designers tool of choice for this role is typically Adobe Photoshop, Illustrator or Fireworks. Next up, we have a relatively new role and that is the interactive designer. There are many definitions for an interactive designer and most of these definitions have a direct relationship with interaction. When you are designing what happens when a user interacts with your web application, you are performing some degree of interactive design. This includes button clicks, view state changes, etc. In the recent past, this interactivity has been created with Flash Professional and most recently, HTML5, JQuery and CSS3 animations. Flash Catalyst creates interactive applications, but that is just a small piece of the puzzle. However, it is a distinct role and web developers may benefit from having dedicated software to fill that role. Thats what Adobe was banking on with its creation of Flash Catalyst. However, to truly fulfill that role, the software would have to be able to pick up the project where the graphic designer left off. This is why Catalyst designers begin their projects by importing Photoshop or Illustrator files. In addition, this product would also have to generate code that could be handed off to the final player in web application development: the programmer or developer. This article will first explore the degree of success Adobe has achieved in fulfilling this goal and the progress they are making with the new release of Catalyst CS5.5. As a technical trainer, I did not experience widespread interest in Catalyst CS5 (version 1.0) and the enterprises that I visit were unclear of its use. While this is somewhat typical of any 1.0 product, the biggest impediment I saw to the adoption of Catalyst was the fact that while the graphic designer to interactive designer workflow was well covered, the workflow generated between the interactive designer and the programmer lacked some important features. First of these was the inability to roundtrip the code back to the interactive designer to implement changes and send the codebase back to the programmer. As you will read later, Flash Catalyst CS5.5 has corrected this situation. In addition, many developers felt the code generated by Flash Catalyst required too much refactoring for it to work in their enterprise applications. With the new roundtrip feature implemented in Catalyst CS5.5 I am starting to see a great deal more interest in Catalyst. In addition, enterprises are now taking a serious look at incorporating Catalyst as a wireframe or prototyping tool which is where I believe its strength lies. Another popular use-case for Flash Catalyst is to create the web applications look by creating and skinning custom components. This involves creating code libraries in Catalyst as opposed to generating the entire Web Applications code which is an area that

lends itself to refactoring by the developers. By creating code libraries in Catalyst, you potentially create a reusable code base of components and skins which developers or programmers can then utilize within their web applications. To summarize, I see the following as valid use cases for Adobe Flash Catalyst CS5.5: Create visually compelling wireframes and prototypes relatively quickly Create skin class files that developers can easily apply to visual controls like buttons, lists, etc. Create visual interactions for a web application or component such that the code can be reused or fairly easily re-created by the programmer

In the next section, well explore these use cases in more detail.

Why and When Should You Use Catalyst?

Probably the most compelling reason to use Flash Catalyst is to build wireframes or prototypes of your application. Many enterprises I visit produce their wireframes anywhere from the back of a napkin to a working design built on HTML and JavaScript. Ive seen PowerPoint and Photoshop files and I personally use some of the many free and commercial web applications (iPlotz, FlairBuilder, Balsamiq). What I like about using Flash Catalyst for prototypes is that you dont have to sacrifice the look simply because its a wireframe. In fact, you can make the wireframe or prototype as simple or as sophisticated as you choose or have the time to develop. A graphic designer can use Photoshop or Illustrator to create a look that can be imported in to Catalyst where the interactive designer can add animations relatively quickly for a more polished presentation of the prototype.

Figure 1. A static wireframe created with iPlotz Version 3.0 www.iplotz.com

07/2011 (25)

27

FLASH DEVELOPMENT

If the prototype is approved you already have reusable artwork in the original Photoshop/Illustrator documents and potentially reusable code in the animations and transitions. Either way, there is no ambiguity in the communication. For example, when verbally trying to describe an animation (slow, but not too slow, and it should fade just a little bit at first and then quickly) much is lost or subject to interpretation. With Catalyst, the animations are precise and you can be assured whether you use the code as is or refactor it, the end result will match precisely with what the interactive designer had in mind. The second use case I see for Catalyst is the creation of custom components and skins. Once again, this is for components with a unique and sophisticated look and feel. Catalyst lets designers create scroll bars, pop-up boxes, list controls and more. No more out-of-the-box look and feel. If you can imagine it, you can create it in Photoshop and give it interactivity in Catalyst. Finally, as stated throughout this article, Catalyst provides a relatively quick (once you understand the timeline) approach to creating animations and transitions. New features in Catalyst CS5.5 provide even more animation enhancements.

Model View Presenter design pattern. Without a great deal of refactoring, it does not implement module-based development and much more. So for those reasons, I believe Catalyst-generated code should not be used as the codebase for an entire enterprise application. Now that weve examined some of the use cases for Catalyst, lets take a look at the new features of Catalyst 2.0 (released as Catalyst CS5.5).

Catalyst CS5.5 New Features

Catalyst CS5.5 has added several new features to satisfy each member of their user base. There are new features aimed at graphic designers, interactive designers and those designers with some programming experience. Each new feature typically results in generated code that is suitable for import and potential reuse into Flash Builder 4.5. The most significant new feature was created for both designers and developers and that is the ability to pass the code from Flash Catalyst to Flash Builder and vice versa at any time in the development cycle. This feature is commonly referred to as a roundtrip workflow. Lets take a detailed look at each new feature.

When Should you Not Use Catalyst?

The Align Panel

Although you can use Catalyst to build an entire application prototype, I dont believe Catalyst should be used to create an entire enterprise application code base, but rather just pieces of the application. Enterprise Application code in its entirety is inherently complex and is best left to the architect and the skillset he or she brings to Web Application Development. This knowledge is invaluable and can certainly not be replaced by a design tool such as Catalyst. Perhaps for a small website, the code base Catalyst generates might be sufficient, but the reality is that most web applications involve back-end services for data access, data persistence and more. The code Catalyst generates typically requires refactoring for it to work within the architecture of most large enterprise applications that implement a Model View Controller or

For graphic designers Adobe has made the popular Align panel (a staple feature in Flash, InDesign and Photoshop) available to Catalyst users. With the Align panel, designers can align objects, distribute space evenly between the top, bottom or center of objects, quickly resize a button (or any object) in one state and then select the remaining buttons and match either the height, width or both height and width of the original button. Objects can be spaced evening between other objects or relative to the art board.

Resizable Applications

With the introduction of Flash Builder 4.5.1 (due out this month) and its huge emphasis on mobile development, the building of multi-screen applications is foremost on the minds of many developers. Creating application

Figure 2. The new Align Panel

Figure 3. The new Project dialog box showing the application is Resizable

28

07/2011 (25)

Whats New In Catalyst CS5.5

code that allows an application to resize itself for wireless phone, tablet and desktop use is paramount. With Flash Catalyst CS5.5 new projects are (by default) built as resizable applications. For developers who need a fixed sized application this feature can be turned off. Figure 3 shows the New Project dialog box with the resizable option in its default state of checked. This

Figure 8. Enlarged view of a constraint handle with no constraint set

Figure 4. The application code for a resizable application. Note the height and width set to 100%

Figure 9. Enlarged view of a center constraint handle. Note the squiggly line indicated a exible space. As the application window resizes the space will reduce or enlarge as needed

Figure 5. The application code for a non-resizable application. Note the height and width set to 1024 x 768

Figure 10. A top constraint

Figure 6. The Art Board Settings and the right angled icon in the lower right of the application window indicate that this is a resizable application

option which can be turned off by deselecting the checkbox results in the code shown in Figure 4. Notice the width and height of 100% each. Figure 4 shows the code generated when resizable is unchecked. Figure 6 shows an application called Cigar Selector that demonstrate the two places that identify the application as resizable. Notice the right angle icon in the lower right corner of the application as well as the Art Board settings (from the main menu bar, choose Modify > Art Board Settings). The resizable application feature allows designers to preview their application and see how it will respond when viewed in various monitor sizes, devices and browser windows.

Constraint-Based Layout

Figure 7. The Cigar Selector app with the content area indicating a center constraint

Hand in hand with resizable applications is the ability to constrict the dimensions of a component while it is being resized. For example you may have a LogIn component that needs to remain in the upper right corner of the application. Constraints allow the designer to ensure that the log-in component is precisely 20 pixels from the top and 20 pixels from the right of application window. Constraints can also be set that ensure that a component is centered within its parent container. Figure 7 shows the Cigar Selector application with the content area (black background, logo, cigar image and enter button) with a center constraint. Figure 8 shows

07/2011 (25)

29

FLASH DEVELOPMENT

a typical constraint handle (the circle above the resize handle) that is not currently set while Figure 9 shows an enlarged version of a center constraint. This center constraint will center the constrained component in the center of the browser window regardless of how much the user resizes their browser window. Figure 10 is an active constraint that constrains the websites logo to the top of the application window. Figure 11 shows the code generated from the use of the center constraint. This code is identical to the code the Flash Builder developer would use. Constraint-based layouts allow the designer to constrain the application or any of its components that have been grouped or added to other components.

Managed layouts let the designer create code that does not require layout refactoring by the developer.

Global Interaction Targeting System

Managed Layouts

The first version of Catalyst supported simple groups for layout which resulting in further refactoring of the code by the Flash Builder developer. Flash Catalyst CS5.5 now supports managed layouts that correspond directly to the code the Flex/Flash developer would write. Possible layouts include horizontal, vertical and tile layouts. Figure 11 shows a group of buttons using Catalysts new layout features and Figure 12 shows the corresponding code that Catalyst generates.

Figure 11. Catalyst-generated code indicating a center constraint

The first version of Catalyst allowed the designer to set interactions on components. The new Global Interaction Targeting System in Flash Catalyst CS5.5 takes this process a step further and provides the designer with the ability to map an interaction to any target component on the application. In other words, the designer can create and trigger an interaction (such as a transition to another view state) from one component that targets an entirely different component. The following screenshots demonstrate this process. The Cigar Selector application includes a status message at the bottom of every screen. As the user navigates from screen to screen the status message component changes its text. Therefore, the navigation button components are triggering an interaction that targets the status text. The first step is to select the component that will trigger the interaction. This is the glossary button as shown in the Catalyst wireframe of the Cigar Selector app in Figure 14. Step two is to click the + Add Interaction button on the Interactions panel as shown in Figure 15. Step three is to click the + Add Interaction button on the Interactions panel as shown in Figure 13. After choosing the trigger (e.g.: On Click) and the interaction (e.g. Play Transition to State) click the Choose Target drop down and select Select other item. This displays the Choose Target dialog shown in Figure 14. The

Figure 12. A component group of buttons designated with a horizontal layout property

Figure 15. The + Add Interaction button used to trigger an interaction from a selected component
Figure 13. The Catalyst-generated code for a managed layout component

Figure 14. Step one of the Global Interaction Targeting System is to select the component that will trigger the interaction

Figure 16. The Choose Target dialog box

30

07/2011 (25)

Whats New In Catalyst CS5.5

dialog box will appear instructing you to navigate to and select the target component for the interaction. After navigating to and selecting the component it will appear as shown in Figure 16. The final step is to complete the interaction in the dialog box shown in Figure 18. The Global Interaction Targeting System allows designers more control over interactions including the ability to allow one component to control another.

Animation Enhancements

interrupted. This is a common occurrence when the user is transitioning from state one to state two and then decides to click a button to return to state one. At this point you can decide whether the user experiences a stop in the transition and then a smooth playback from its current location or simply snap to the end of the transition and then playback from the end. In addition to these features, Flash Catalyst CS5.5 now supports animating property changes such as filters, strokes, fills, font size, and font color changes.

Animating has been a primary concern of Flash Catalyst since it was introduced in CS5.0. With Catalyst CS5.5, you have a wider variety of animations to choose from including built-in auto-reverse of your animations. A classic example of the need for this auto-reverse is a transition played when a component is moved from one view state to another. For a consistent design experience for the end user, an identical transition should be played whenever the object moves back to its original position. Simply checking the Automatic Reverse checkbox will accomplish this. With Catalyst CS5.5, you can set the individual effects that make up your transitions (e.g. resize, fade, etc.) to repeat, but you can also designate the entire transition to repeat. Another animation enhancement is the ability to dictate what should happen when a transition is

The Common Library Panel

As I suggested earlier, I believe that the strength of Flash Catalyst lies in its ability to rapidly create wireframes and prototypes which can be used to communicate the look and feel of an application to upper management and end-user clients for preliminary usability testing and general feature and requirements input. Toward that end, Adobe has included the new Common Library Panel which contains pre-built assets as shown in sidebar 1.
*** Sidebar #1: ***

Flex Components from the New Common Library Panel. Components with editable skins: Button Check Box Data List Horizontal Scrollbar Horizontal Slider Radio Button Toggle Button Vertical scrollbar Vertical slider Button Bar

Components whose skins cannot be edited:


Figure 17. The selected component

Button Bar Combo Box Drop-down Numeric Stepper Tab Bar

*** End of Sidebar #1 ***

Figure 18. The completed interaction

Figure 19. The Common Library panel used for rapid creation of prototypes and wireframes

07/2011 (25)

31

FLASH DEVELOPMENT

the creation of these known components and/or skins for the components the developers are currently creating. Any components that extend SkinnableComponent will appear in the Skinnable Component list in Flash Catalyst. Once the designer has completed creating the skins, they send the developer their newly created Flash Catalyst library and the designer can use the skins in the Flash Builder application.

Figure 20. Opening a Catalyst project from Flash Builder 4.5

The New Flash Builder/Flash Catalyst Workflows

Due to the new ability to roundtrip the code between applications, new workflows are now available between designers and developers. In the first workflow, the designer begins the process with a Catalyst-generated wireframe. The Catalyst project is then saved with File > Save As FXP. The FXP project can then be imported in Flash Builder via the Project Menus new option as shown in Figure 20. In this workflow you would be exchanging .fxp files between designers and developers which can be prone to versioning issues. If you are both the designer and developer and own both Flash Builder 4.5 and Catalyst CS5.5, you can exercise the options shown in Figure 18 including (from Flash Builder 4.5) Edit Project in Flash Catalyst This would launch the designers version of Flash Catalyst and open the fxp file. When the design work is finished, the designer can return to Flash Builder and choose the option (shown in Figure 18) Resume Working on Project in Flash Builder. A Cancel Editing Project in Flash Catalyst is available also. When transferring projects from Flash Builder 4.5 to Catalyst CS5.5, Adobe recommends exercising the Run Compatibility Checker option (also shown in Figure 18) to make sure than you have not introduced any code that would prevent Catalyst from opening your FXP file. Another workflow available to designers and developers is the creation and subsequent exchange of Flex Library Projects. This workflow is helpful when designers and developers are attempting concurrent development during a project. The software architect and his team can begin coding the application per their usual processes. They will need to create a Flash Catalyst Compatible project. In most enterprise applications, the architect will create a framework or code library of components as Flex Library projects. The components that have been designated for skinning may be written in ActionScript and should extend the SkinnableComponent class. In the meantime, the Catalyst designer can create Flex Library projects for

Further Integration in the Cigar Selector Application

The Finished Application

Figure 19 shows the finished Cigar Project displaying the search screen that was built using components from the Common library (which may be skinned at any time). The actually search logic was implemented in Flash Builder.

Summary

Flash Catalyst CS5.5 provides some significant new features making it well worth looking at for enterprise application development. While not suitable for a full application, it is an excellent tool for creating wireframes, working prototypes (Catalyst allows for the creation of mock data) and skinning components. If you would like to watch a video workshop and learn how to create the Cigar Selector application with Catalyst visit [insert url] for a discount coupon at https:// partner.video2brain.com/kevinruse/.

KEVIN RUSE

Kevin Ruse is President and Senior Trainer at Kevin Ruse + Associates Inc. (www.kevinruse.com). He currently provides training in all things Adobe as well as HTML5, CSS, JavaScript, XML, XSLT, ColdFusion, ActionScript, Java and more. Kevin has conducted training at some of the leading companies in Silicon Valley including Cisco, Adobe, Google, Applied Materials, KLA Tencor, EMC, Avaya, Sony and many more companies throughout the United States and Europe.

32

07/2011 (25)

FLASH DEVELOPMENT

ActionScript 3.0 Best Practices


Using the EventCollector Class
A few weeks ago, I worked on a project based on the Youtube AS3 API and I was really surprised how Flash developers still have concerns with event management.
What you will learn
Basic of OOP Basic of Flash Player event management How to include SWC libraries within AS3 projects

What you should know


How to prevent memory leaks in AS3 How to use the EventCollector class How to create well-structured OOP code for more reusability in a modular approach

hen I started the migration from SPAS 2.0 to SPAS 3.0, in 2006, one of the first classes I created was the EventCollector class. This class has been especially designed to solve these problems. So I have decided to share it within an autonomous package, even if it is still a core part of the SPAS 3.0 API. That means the EventCollector class is now compatible with Flash, Flex (Flash Builder and Flex SDK) and all of the available ActionScript 3.0 APIs and projects on the Web.

You can download trial ActionScript 3.0 environments from the Adobe Website: http:// www.adobe.com/ You can download a free ActionScript 3.0 environmen2ts from the FlashDevelop Website: http://www.flashdevelop.org/

Events and chaos

Requirements

In order to go through this tutorial, we assume that you have an ActionScript 3.0 environment set-up and that you are familiar with the basic concepts of event handling.

Prerequisite knowledge
Experience in developing ActionScript OOP applications. Experience in using SWC ActionScript libraries. Experience in using an ActionScript 3.0 objects profiler is a plus but not necessary.

Products
You can download the collector API from the SPAS 3.0 Website: http://www.flashapi.org/

The event DOM-based model, introduced with ActionScript 3.0, was a fantastic improvement for building complex applications. (Maybe some of you guys remember the good old Delegate class.) But if we pay attention to the memory leaks issues in ActionScript, arguably the persistence of object references through events is responsible in most of the cases. Because the event model is very flexible and easy-to-use, event listeners are often disseminated all over the code, without any rules or well defined structures. The fact is that if you implement a large number of unorganized lines of code within an application, you introduce chaos in the computer! Now, just imagine a complete on line music editor, with tens of modules called, created, and displayed on the fly. Each module is composed of many different classes which are responsible for synchronous or asynchronous treatments (loading and saving data, playing back music, checking for music theory rules, etc.). Such an application cannot be made if you do not take care of memory usage. Unfortunately, there is no way to easily fix event management issues. Each

34

07/2011 (25)

ActionScript 3.0 Best Practices: Using the EventCollector Class

event listener must be removed before deleting unused modules and this could become really fastidious when you have to check hundreds of classes.

its robustness, efficiency and flexibility have been welltested for many years.

The EventCollector class

Basics

As we commonly say: The simplest ideas work the best. And the event collection concept is probably one of the most simple reusable piece of code ever written in ActionScript. We know, that (fortunately) there are no mechanisms to automatically remove event listener references when setting an object to null. But if we consider the process of deleting an object, we would never have to know the number or type of event listeners associated to it and what they are doing. Our only concern should be to ensure their destruction. That is precisely what the EventCollector class does! So, it has been designed with two main goals: provide a convenient API to gain more time and write well-structured code, ensure to delete event references in all cases.

Moreover, the EventCollector class has been the SPAS 3.0 core event manager since 2006, which means that
Listing 1. The addEvent() method signature

Before exploring the class API, remember that EventCollector instances must be accessed from any part of your object, but always hidden from the public API. (See Chapter 8 for exceptions.) Most of the time, we will only use two methods for managing events: addEvent() and removeEvent(). All parameters of the addEvent() method are the same as the parameters of the addEventListener() method, defined by the IEventDispatcher interface, except the first one, which is the listener object itself. Note that the event and the func parameters of the addEvent() method represent respectively the event and listener parameters of the addEventListener() method. The common use of the EventCollector class is shown Listing 2. The following code does the same without using an EventCollector instance: see Listing 3. To remove the registered event handler, you call the removeEvent() method with only three parameters: the listener object, the event type and the associated function. The code below shows how to remove the event handler we added above: see Listing 4.

addEvent(obj:IEventDispatcher, event:String, func:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void

Listing 2. EventCollector class common use


// Creates a new // Creates a new EventCollector instance Loader instance

var evtColl:EventCollector = new EventCollector(); var loader:Loader = new Loader();

// Adds a new event handler to the event collection evtColl.addEvent(loader.contentLoaderInfo, Event.COMPLETE, loaderComplete);
function

loaderComplete(e:Event):void {

trace("Data loaded");

Listing 3. Common use of the IEventDispatcher API


// Creates a new Loader instance loader object

var loader:Loader = new Loader();

// Adds a new event handler to the

loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete);

Listing 4. The removeEvent() method


evtColl.removeEvent(loader.contentLoaderInfo, Event.COMPLETE, loaderComplete);

07/2011 (25)

35

FLASH DEVELOPMENT

Listing 5. A sample class for creating random events


package { import flash.display.Sprite; import flash.events.Event;

public class RandomEvents extends Sprite { public function RandomEvents() { super();

init();

private var _sprite:Sprite; private function init():void {

createObj(); deleteObj();

private function createObj():void {

var i:int = Math.round(Math.random() * 100) + 1;

for (; i >= 0; i--) {

_sprite = new Sprite();

var child:Sprite = new Sprite();

child.addEventListener(Event.ENTER_FRAME, fooBar); } _sprite.addChild(child);

private function deleteObj():void {

_sprite = null;

// Child sprite objects can not be garbage-collected because // event are still fired. }
private function fooBar(e:Event):void {

trace("Called"); /*

// Sample random action: var tgt:Sprite = tgt.x = tgt.y = */ }


private function getRandomPos():Number {

e.target;

getRandomPos(); getRandomPos();

return

(Math.random() * 1000);

36

07/2011 (25)

ActionScript 3.0 Best Practices: Using the EventCollector Class

This is the minimal API you need to know to work with the EventCollector class. The event collection process provides many more methods to implement mechanisms based on the IEventDispatcher interface (e.g. hasRegisteredEvent()), or custom convenient methods (e.g. addEventCollection()). For more information about methods of the EventCollector class, go to the SPAS 3.0 documentation at: http://www.flashapi.org/spas-doc/.

Benefits of using the EventCollector class

In the previous section we saw that the EventCollector class behaves exactly as objects that implement the IEventDispatcher interface do. At this point, it does not solve the problem raised earlier. For example, lets imagine an object which is responsible for creating and deleting a random range of particle objects. The following sample class illustrates such an object see Listing 5. In this example, the createObj() method creates a random number of sprite objects and adds them to the display list of the _sprite instance. Then, the deleteObj() method sets the _sprite instance to null. If you do not associate some event listeners to its children, setting the _sprite instance to null will make all the contained sprite objects eligible for garbage collection. But as we have added an event listener to each child, all of them remain in memory. This class reproduces a common coding case often encountered across the Flash community. The best way to prevent the issue described in this example is to use the removeAllEvents() method provided by the EventCollector class. As we said in the previous chapter, welldesigned applications imply that we do not
Listing 6. The removeAllEvents() method in action
private function deleteObj():void {

need to know anything about the registered events; we just have to remove all of them. When calling the removeAllEvents() method, all events listeners registered through the EventCollector instance are automatically deleted for all added objects. Replace the preceding deleteObj() method by the following one and launch the Flash Builder, or FlashDevelop, objects profiler to compare the result in both cases: see Listing 6. This is probably the most simple and convenient mechanism to prevent memory leaks due to event management. As you can see, the EventCollector class respects the assumptions set out in Chapter 4: gaining time and ensure deleting event references in all cases.

Best practices for Modular OOP in the Flash Platform

The sample class in Chapter 6 is probably too short and too basic to illustrate the real benefits of using the EventCollector class for managing all of your events within a Flash application. In Chapter 3, we talked about managing hundreds of classes. And inevitably, this leads us to think about how we design our applications on the Flash Platform. Remember what we said above: The simplest ideas work the best. Bertrand Meyer introduced Modular OOP about 15 years ago (MEYER, 1997). As everything has already been theorized, we just have to apply some of these concepts to make better software. By combining modular design (consider classes as modules) and a few simple techniques, such as the

_evtColl.removeAllEvents(); _sprite = null;

// Deletes all event listener references. // All sprite objects can be garbage-collected and memory being freed. }

Listing 7. AS3 destroying process sample


private function deleteObj():void {

_evtColl.removeAllEvents(); evtColl.finalize(); evtColl = null; _sprite = null;

// Deletes all event listener references. // Deletes all internal persistent objects used within the EventCollector instance. // Deletes the EventCollector instance. // All sprite objects can be garbage-collected and memory being freed. }

07/2011 (25)

37

FLASH DEVELOPMENT

Listing 8. Basic implementation of the destroy() method


public function destroy():void {

_evtColl.removeAllEvents(); _evtColl.finalize(); _evtColl = null;

// Write the rest of the destroying statement here... }

class, it should be possible to definitely close discussions about memory leaks on the Flash Platform. A base rule should be accepted by everyone: Each time a main object is responsible for creating a strong reference in the memory to any other object, it should provide a visible mechanism for removing this reference. This is a global concept, so visible means accessible by the consumers of the main object. For example, SPAS 3.0 API implements such a process through the finalize() methods. According to this, if we consider the sample class from Chapter 6, the deleteObj() method should be rewritten as shown Listing 7. For a more global transcription, regarding ActionScript 3.0 practices, the original rule could be simplified to this one: Each time a class instance is responsible for creating a BitmapData instance or an event listener, it should provide a public method for deleting the reference of this object. Moreover, the logical name of such an action should be destroy. And that is where the EventCollector class is really interesting to use, because we no longer need to pay attention to the event listener references we have created to delete them later. A single command is used to carry out this task: see Listing 8. By applying this code snippet to all of your developments, you could create much better reusable libraries, components or applications.
EventCollector

The EventCollector instance must be a singleton. The MVC pattern should be considered as a module itself. It means that EventCollector singleton must not be used by an object which does not belong to this module. (Principle of Retention of Information.) The removeAllEvents() method must be the first action called within the destroying method implemented by the model. So, the structure of events management inside each object must be designed to respect this rule. (This is based on the principle of Modular Composability.)

Even if it is technically possible to do that, it seems wise to discourage the use of such practices! Unfortunately, the MVC pattern is not the best way to simplify the management of memory leaks. Thus, whatever the considered solution, it will not be easy to implement it. In any case, you should implement a destroying method each time the rules introduced in Chapter 7 are confirmed.

Where to go from here

EventCollector and MVC

When you are designing an object-oriented application, it is not advisable to share functionalities across several different modules. The direct consequence is that sharing an EventCollector instance, between two or more classes, is not good practice. However, it is always possible to implement a shared EventCollector instance in the MVC pattern. But to be efficient, you must follow some basic rules to design the structure of the pattern:

In this article, we learned how to use the EventCollector class to simplify and improve the management of event handling in ActionScript 3.0. By now, you should be able to implement the EventCollector API in your existing and new projects by using the concepts explained in Chapter 7. A Javascript portage of this class is available on the EventCollector page at: http://www.flashapi.org/ eventcollector/. We need your feedback to add functionalities to the collector API, so feel free to post your comments on this page. To be informed of new releases, latest information and documents about the collector API, or support SPAS 3.0 projects, follow us on the SPAS 3.0 Facebook page at: http://www.facebook.com/flashapi.

PASCAL ECHEMANN
Pascal has a 3 years university degree in Computer Siences majored in Multimedia and an 2 years technical degree in Visual Communication majored in Multimedia. He is an ActionScript developer who focused on Flash-based tools to produce human-machine interfaces. Pascal has spent the past ve years to design and develop the Swing Package for ActionScript API (SPAS), to help ash developers to easily create RIAs with the Flash Platform.

Bibliography

[MEYER, 1997] Bertrand MEYER, Object-Oriented Software Construction, second edition, Prentice Hall, 1296 pages, January 1997.

38

07/2011 (25)

DYNAMIC PROGRAMMING

A Gentle Introduction To Dynamic Programming


Dynamic programming is a method for solving complex problems by breaking them down (when applicable) into simpler subproblems.

What you will learn


Foundation of Dynamic Programming How to design an algorithm starting from real life issues Improve the performance of recursive functions

What you should know


The foundation of OOP Loops, conditional statements and Array What is a recursive function

hen applicable, the method takes far less time than naive methods. The key idea behind dynamic programming is quite simple. In general, to solve a given problem, we need to solve different parts of the problem (i.e. subproblems) and then combine the solutions of the subproblems to reach an overall solution. Dynamic programming sometimes is considered as branch of applied mathematic, for this reason most developers consider it too complex to be applied to a real life scenario. Imagine dynamic programming as a different way of thinking that can solve problems more efficiently. Dynamic programming is a slightly different way to design an algorithm. An algorithm is just the outline or idea behind a program. In this article algorithms are expressed in pseudo-code (i.e. something resembling C or Pascal, but with some statements in English rather than within the programming language). It is expected that one could translate each pseudo-code statement to a small number of lines of actual code, easily and mechanically. Its possible to think to dynamic programming as to a sequence of decisions like every facet of life that entails a sequence of decisions. In real life many cases decisions must be made without knowing their outcomes, like in the following activities:

Investing Gambling Playing tennis Driving

Nobody knows in advance if an investment will generate revenue or if the number on which someone placed bets on will be the one on which the roulettes ball will fall. Even more nobody knows if the first strike playing tennis will be the winning one or can predict all the possible traffic jam scenarios when driving. The term sequential decision process is used to describe an activity that entails a sequence of actions taken toward some goal. Sequential decision processes as diverse as playing tennis and investing seem to have little in common, but its the mathematical representation of such activities that share several important features. In the context of algorithms the Bayesian theorem really help to better understand what dynamic programming is, it states

If you can postpone a terminal decision in order to observe, cost free, an experiment whose outcome might change your terminal decision, then it is strictly better to postpone the terminal decision in order to acquire the new evidence

40

07/2011 (25)

A Gentle Introduction To Dynamic Programming

Dynamic programming was born of the realization that certain features recur again and again when sequential decision processes are analyzed, in fact one of the key point that distinguish a dynamic programming algorithm is that it consider already discovered solutions during its execution. Obviously, as stated in the Bayesian theorem, the consideration of already discovered solutions should be cost free or, at least, should not be a procedure that impact too much the efficiency of a program. One of the most common definitions of dynamic programming states that it is the collection of mathematical tools used to analyze sequential decision processes, for this reason we can consider dynamic programming as a branch of applied mathematic. As most of the applied mathematics algorithms a dynamic programming one can bear fruit in the form of insight numbers The insights usually come from theory The numbers from computation

For brevity since now the DP acronym will be used to refer to dynamic programming. One of the most complete definitions of DP is the following one DP is an algorithmic technique which is usually based on a recurrent formula and one (or some) starting states. A sub-solution of the problem is constructed from previously found ones. Keeping in mind this definition its possible to start making an analysis to find a solution for the following problem: given a list of N coins, their values (V1, V2, ... , V VN ), and the total sum S find the minimum number of coins the sum of which is S. Think to this problem in a less general way and focus on a more practical version of the same problem: given coins with values 1, 3, and 5 find the minimum number of coins needed to reach the value of 11. Going back to the DP definition the first thing to do is to find a starting state. A state is an optimal solution with which its possible to find a solution for the next state so it is a way to describe a situation, a sub-solution for the problem. In the problem outlined a state would be the solution for sum i where i S. An approach to solve the problem is to figure out the solutions for the sums (i.e. states) 0,1,211 basing each one on the results already discovered.
Listing 1. Minimum number of coins pseudocode
VAR S int , the sum to reach

Dynamic programming 101, a basic example

A practical approach brings to the definition of dynamic programming algorithms. Write down ideas before starting to outline an algorithm is the first step to design a powerful algorithm. In order to clarify what have been exposed so far, imagine being in an elementary inventory situation in which is very important to store enough liquid (lets say fuel) into a bin in order to avoid to go out of stock. Someone can determine that an optimal solution is to draw a line on a bin and fill it each week to that line. This is a sort of insight that can be obtained by theory but it rules out more complex control policies. Control policies, especially where to draw the line, came from computation usually done on a digital computer with the help of several algorithms.
Table 1. Minimum number of coins solution

SUM
0 1 2 3 4 5 6 7 8 9 10 11

Min nr. of coins (1, 3, 5)


0 1 2 1 2 1 2 3 2 3 2 3

Coin value added


0 1 1 3 1 5 3 or 1 1 3 3 5 1

Sum to which is added


0 0 1 0 3 0 3 or 5 6 5 6 5 10

FOR i = 1 to S FOR

VAR N

VAR coins

SET min[0] equal to 0

SET min[i] equal to Infinity for all of i Array, available coins

VAR min

Array , store all the states

int, total coins

j = 0 to N - 1 IF Vj <= i AND min[i - Vj] + 1 < min[i] THEN SET min[i] = min[i - Vj] + 1 ENDIF

ENDFOR ENDFOR

PRINT min[S]

07/2011 (25)

41

DYNAMIC PROGRAMMING

Having found the minimum number of coins which sum up to i its quite easy find the next state (i.e. the solution for i + 1) and so on until the problem is completely solved. One of the possible ways to outline a DP algorithm is to study solutions based upon an empirical approach. Its quite intuitive to start assuming that a state for this problem is a possible sum of coins (e.g. from 0 to 11) so that it can be represented as the solution for sum i, where i S. Its possible right now to mark that for state 0 (sum 0) there is a solution with a minimum number of 0 coins, then, moving to state 1 (sum 1), there is a solution with a

minimum number of 1 coin. With the same approach the solution for the state 2 (sum 2) can be found identifying that the only coin which is less or equal to this sum is the first coin, having a value of 1; the optimal solution found for sum (2-1) = 1 is coin 1; this coin 1 plus the first coin will sum up to 2 so there is a solution with a minimum number of 2 coins. In the following table there are the solutions for each state, exploring each solution its possible to identify a general solution to the problem. The following table contains the solutions for each state of the problem; its quite useful to notice that there are two different solutions for the sum 6, both the solutions are efficient and cost free but the second one should be a little bit more Listing 2. Initialization of the data and processing of the available values efficient because its closer to the state 6 private function init():void{ (Table 1). The solution to the problem can be represented in a more general way with the following snippet of pseudocode see Listing for(var i:int = 0; i <= sumToReach; i++){ 1. Actually whats happening in the code can minimums[i] = Number.POSITIVE_INFINITY; be summarized in few steps:
} minimums[0] = 0;

} protected function processData():void{


for(var i:int = 1; i <= sumToReach; i++){ for (var j:int = 0; j < availableValues.length; j++){ if(availableValues[j] <= i && minimums[i -

Creation an array with a specific number of indexes (the same of the sum to reach) Definition of the first known state (i.e. the sum 0) Initialization of the available coins Iteration over the states and the available coins to determine the number of coins needed to reach a specific sum Printing of the last index of the array that contains the sums In ActionScript 3.0 the previous steps can be performed with the definition of a couple of methods that assume the declaration of the members minimums (i.e. the array with the number of values available to reach each state of the problem), sumToReach (i.e. the value to reach) and availableValues (i.e. the array that contains the available values to use to reach a specific sum; see Listing 2)

availableValues[j]] + 1 < minimums[i]){

minimums[i] = minimums[i - availableValues[j]] + 1 }

} }

Dynamic programming and recursion


A recursive function is a function that breaks down a problem in smaller problems and solves them calling itself until the problem is solved (i.e. an exit condition is verified). Recursive functions are useful in evaluating certain types of mathematical functions or in order to parse certain dynamic data structures such as linked lists or binary trees.

_minimumValuesNeeded = minimums[sumToReach] }

42

07/2011 (25)

A Gentle Introduction To Dynamic Programming

The recursive functions are characterized by the process in virtue of which the value of a function for some argument is defined in terms of the value of that function for some other (in some appropriate sense smaller) arguments, as well as the values of certain other functions. The drawback of such an approach is that, in some cases, is it possible to end up doing more work than necessary in the algorithm (i.e. the cost starts increasing). A basic sample of a recursive function is the Fibonaccis algorithm
PROCEDURE fibonacci

return fib(n-1) + fib(n-2);

The following snippet of code is the same implementation of the one above but it consider and store previous discovered solutions into an Array
var fibarr:Array = [];

function smartFib(n:int):int { if (n == 1 || n == 2){ }else{ return 1;

if (fibarr[n] == null){ }

ARGUMENTS

int

fibarr[n] = smartFib(n-1) + smartFib(n-2);

IF n = 1 OR n = 0 THEN RETURN 1

} }

return fibarr[n];

ELSE

RECURSION (n-1) + (n-2);

The execution time and the number of recursive calls is pretty different as shown in the logs generated by the calculation of the number 20
======== fib ======= The result is 6765

ENDIF ENDPROCEDURE

Calculating fibonacci number for 20 Performed in 5 ms with 6764 recursive calls ===== smartFib ====== The result is 6765

This algorithm is pretty expensive because it executes the same calculation more than ones. Lets consider the following usage example
fibonacci(5);

Calculating fibonacci number for 20 Performed in 1 ms with 18 recursive calls

The calculations are performed on the integers 5, 4, 3, 2, 1, 2, 3, 2 and 1 without considering the already discovered solutions recomputing the same subproblems over and over again. There are several approaches to make this algorithm more efficient. A possible solution is to use an iterative algorithm (i.e. one that uses loops instead of recursion); another one is to store the already discovered solutions in order to reduce the number of performed calculations. The storage of previous discovered solutions implies the usage of memory but the amount of memory consumed by a solution like this is so small comparing to the efficiency can be reached with a DP approach. The following snippet of code represents the recursive implementation of the Fibonaccis algorithm that does not consider previous discovered solutions
function fib(n:int):int { if (n == 1 || n == 2){ } return 1;

The shortest path problem

The shortest and longest path problems represent one of the most common sequential decision processes; both of them exist in many varieties but all are elaborations of the optimization process in a directed network.

Mathematically speaking a directed network consists of a non empty set of nodes S and a subset of Cartesian product (S x S) called direct arcs and usually named T. The network represented above consists of the nodes 1,2,3,4,5 and of the following Cartesians products (i x j) T1 = 1 x 3 T2 = 1 x 2

Figure 1. Directed network

07/2011 (25)

43

DYNAMIC PROGRAMMING

T3 = 3 x 2 T4 = 2 x 4 T5 = 4 x 1 T6 = 4 x 5 Direct arcs (i, j) suggest the possibility of direct movement from node i to node j. The movements from node i to node j represent the path into a directed network. Mathematically speaking a path is a sequence of at least two nodes that has the property that (ik, ik + 1) is a direct ark for k = 1, 2, , n. The network depicted in Figure1 contains paths (2, 4) and (1, 3, 2) but not the path (1, 2, 3), directed arc (i, j) is said to emanate from node i and to terminate to node j. The arrows represent the direction an arc emanate from a node. Its really hard to fully explain the theory behind the directed networks in few lines and even more this is not the aim of this paper. The important thing to understand is that directed networks are an approach to the analysis of complex problems (natural, social, technological, etc.) and that in order to start using them its not required to be a mathematics expert. A directed network may be cyclic or acyclic, a network that contain at least one cycle (path with i1 = in is called cycle) is called cyclic if it doesnt contain a cycle is called acyclic. The prototype of all dynamic problems is to find the shortest or the longest path through a finite acyclic network. The network depicted in Figure 2 is the representation of the one-way routes from a point of interest to another one in a map; the orange numbers are the time needed to traverse an arc (i.e. move from node i to node j). A myopic solution should be to follow a path that consists of nodes the arc of which report the shortest time to reach the next node. The resulting path of such kind of calculation is 1, 2, 4, 6, 8, 9 and the time to reach the end node is 27. With a cursory examination its easy to find that the shortest path is instead made up by the nodes 1, 3, 4, 5, 7, 9 and that the time needed to reach the end node is 19. A more general solution can be expressed as following

fi = the minimum travel time from node i to node 9

where fi is the algorithm that calculate the shortest route from one point to another one. Keeping in mind the definition of DP already provided its easy to find a starting state to solve the problem f9 = 0 f1 = 19 When the end node of the network has been reached the remaining travel time is 0 and moreover at the beginning of the network the travel time is the sum of the travel time of each specific arc (i.e. the orange numbers). The algorithm tij is the way to denote the travel time for each arc (i, j), for this reason the expression tij + fj represents the travel path from the node i to node 9 that first traverse the arc (i, j) and then travels as quick as possible from node j to node 9. As it is the path from i to node 9 it has to be at least as large as fj so, in other words, it means that fi <= tij+ fj Some j satisfies the inequality as an equation so that fi = min{tij+ fj} The following table report the empirical computation of fi (decreasing i starting with i = 8) in order to satisfy the equation fi = min {tij+ fj}. The first column contain the fn item on which the calculation is performed (i.e. fi), the second one is the time needed to traverse to the next possible node (i.e. tij (s)), the third one the time needed from a specific node to reach the destination point (i.e. fj (s) (j, value)), the fourth one the values to be summed to calculate the remaining time (i.e. Values) and the last one the nodes that cooperate to define the shortest path to the destination (i.e. Path nodes). The values that represent the time still needed to reach the end of the network are based on already discovered ones (Table 2). The equation states to consider the minimum value found so the result of the empiric calculation is that only the nodes attaining the minimum are preserved as well as their arcs. The following picture is the representation of the fastest path from each node to node 9 not just from node 1 to node 9, the nodes that are on the same path are 1, 3, 4, 5, 7, 9. The DP algorithm produces the same results of the cursory examination so its assumed to be correct, as stated before the DP algorithms often start from insight and empirical solutions.

Figure 2. Shortest path network representation

44

07/2011 (25)

A Gentle Introduction To Dynamic Programming

Sequential decision processes usually represent decision problems involving trade-off between immediate costs and future costs, the myopic solution doesnt consider the node at which an arc terminates because it select as the shortest route the next shorter travelling time. The time spent on the empiric calculation and on the equation definition is the prototype for the dynamic programming equation.

Longest common subsequence problem

Dynamic Programming is a powerful technique that can be used to solve many problems in time T(n2) or T(n3) for which a naive approach would take exponential time. DP is a general approach to solving problems, much like divide-and-conquer is a general method, except that unlike divide-and-conquer, the subproblems will typically overlap and are used to solve the next one. The cost of an algorithm in a program is a critical aspect because it can significantly impact on performances. In order to keep the cost low DP follow a couple of standard ways to progress memorization converting from top-down to bottom-up

Another very common problem in DP is the longest common subsequence problem (for brevity since now LCS). The LCS problem is as follows We are given two strings: string S of length n, and string T of length m. The goal is to produce their longest common subsequence: the longest sequence of characters that appear left-to-right (but not necessarily in a contiguous block) in both strings.
Table 2. Shortest path solution

The problem can be solved comparing the two strings; in the case S and T have a different length the desired subsequence has to ignore the ending elements of one of the two strings, in the case S and T have the same length all the characters have to be considered. As subproblems the algorithm will look at the LCS of a prefix of S and a prefix of T, running over all pairs of prefixes. For simplicity, lets worry first about finding the length of the LCS and then we can modify the algorithm to produce the actual sequence itself. Theoretically speaking the algorithm just fill out a matrix row by row, doing constant amount of work per entry, so this takes T(mn) time overall. The work actually performed is a comparison between the chars of the two strings at specific indexes. The final answer (i.e. the length of the LCS of S and T) is in the lower-right corner. To find the common sequence, the algorithm just walk backwards through matrix starting the lower-right corner. If either the cell directly above or directly to the right contains a value equal to the value in the current cell, then move to that cell (if both to, then chose either one). If both such cells have values strictly less than the value in the current cell, then move diagonally up-left, and output the associated character. This will output the characters in the LCS in reverse order.

fi
f8 f7 f6 f5 f4

tij (s)
10 3 7 15 7 4 15 7 3 3 4 12 6 1

fj (s) (j, value)


(9, 0) (9, 0) (8, 10) (9, 0) (7, 3) (5, 10) (7, 3) (8, 10) (6, 15) (4, 14) (6, 10) (5, 10) (4, 14) (2, 20)

Values
10 3 7 + 10 15 + 0 10 14 18 17 18 17 19 22 20 21

Path nodes
9 9 8 9 7 5 7 8 6 4 6 5 4 2

Figure 3. Shortest path network result

f3 f2 f1

Figure 4. LCS problem implementation

07/2011 (25)

45

DYNAMIC PROGRAMMING

The DP topic is pretty vast and complex; in order to start to be procient in it the following links should be a good starting point http://blogs.msdn.com/b/ericlippert/archive/2004/07/21/recursion-and-dynamic-programming.aspx http://en.wikipedia.org/wiki/Fibonacci_number#List_of_Fibonacci_numbers http://www.topcoder.com/tc?d1=tutorials&d2=dynProg&module=Static http://en.wikipedia.org/wiki/Dynamic_programming http://mat.gsia.cmu.edu/classes/dynamic/node1.html http://www.thatsjava.com/java-programming/145079/ http://people.csail.mit.edu/bdean/6.046/dp/ http://en.wikipedia.org/wiki/Levenshtein_distance http://en.wikipedia.org/wiki/Viterbi_algorithm http://plato.stanford.edu/entries/recursive-functions/ http://www.ics.uci.edu/~eppstein/161/960109.html http://papers.ssrn.com/sol3/papers.cfm?abstract_id=911577

Resources

There are several books and papers about DP, the following list is not omni-comprehensive one but it can be considered as the DP one can provide solid basis about DP Dynamic programming, models and applications (Eric Denardo) The University of Texas at Austin, Lecture 8 Dynamic Programming (Vijaya Ramachandran) The Viterbi Algorithm (David Forney) Practice Dynamic Programming Problems (Brian Dean) Application of Dynamic Programming in dynamic image sequence analysis (Sun Zheng) A FPGA-Based Viterbi algorithm implementation for speech recognition system (Fabian Luis Vargas and others) Mathematical Modeling Techniques (Aris Rutherfort)

Consider a practical example and search the LCS of the following strings ABAZDC BACBAD

Conclusions

The algorithm will fill out a matrix like the following one and running backward the matrix the output will be DABA that is the LCS between the two strings.
B A B A Z D C 0 1 1 1 1 1 A 1 1 2 2 2 2 C 1 1 2 2 2 3 B 1 2 2 2 2 3 A 1 2 3 3 3 3 D 1 2 3 3 4 4

The DP topic is a challenge for all the programmers, studying the solutions already discovered each programmer can really open his / her mind. This paper is the result of the some studies performed on the topic and would be only a guide from which everyone can start, feel free to contact the author for deeper discussions, suggestions and questions.

GIORGIO NATILI
Giorgio Natili is an Adobe community expert, a W3C member and a Java User Group manager. He is head of his own company GNStudio, which has been operating in the web development eld for the past 9 years. His area of expertise focuses on Adobe Flash, Air, Flex, ColdFusion, Flash Media Server, RED5 and their integration, as well as accessibility both in html and Flash. Since ve years his interests have broadened to include developing mobile applications and e-learning tools, for this reason he worked a lot with Flash Lite and Symbian C++, most recently he is focusing on Android development. He follows the agile development practices since three years and has a lot of experience as technical leader in small / medium size teams. He also works on various education initiatives to spread awareness on accessibility issues, especially to ash developers. He was speaker during the Adobe Max, the 360|Flex, the FITC, several Flash Camps all around the world and right now is a proud speaker of the Flash and The City.

From a practical point of view the following diagram shows up the classes involved into an ActionScript DP solution to the problem. In order to get the source and a more detailed explanation of the implementation just open the following link http://www.mxml.it/index.php/2011/06/04/ longest-common-subsequence-problem/ longest-common-subsequence-problem/.

46

07/2011 (25)

INTERVIEW

Interview with

Kevin Ruse

Kevin Ruse is President and Senior Trainer at Kevin Ruse + Associates Inc. (http:// www.kevinruse.com/). He currently provides training in all things Adobe as well as HTML5, CSS, JavaScript, XML, XSLT, ColdFusion, ActionScript, Java and more. Kevin has conducted training at some of the leading companies in Silicon Valley including Cisco, Adobe, Google, Applied Materials, KLA Tencor, EMC, Avaya, Sony and many more companies throughout the United States and Europe.

You are an author. Could you tell us more about your latest book?

I wrote the Introduction to Flash Builder 4: Full 5 Day Course to accompany my training seminars. It covers all the fundamental topics for the beginner or advanced developer who would like to develop Flex/ Flash applications with Flash Builder 4.0. The topics range from basic layout all the way to unit testing and debugging. The course is typically 5 days of Flash Builder training but it also covers an overview of the entire Flash Platform.

also go into the details of the Flash Player including the just-in-time compiler, interpreter and garbage collection.

What kind of criteria do you use to select the topics for the book or article?

To whom is it addressed?

The book is suitable for the beginning programmer due to its overview of both Object Oriented Programming and ActionScript 3.0. At the same time I have used the book while teaching experienced Java, .NET, C# programmers (with 10 + years experience) who are new to the Flash Platform. It covers the unique features of both ActionScript and the Eclipse-based IDE of Flash Builder as well as the main paradigm shift for these developers which is mainly the runtime (Flash Player), the fact that the developer is making movies and how the timeline might affect their approach to application architecture. The book and live-instructor-led course

I basically rely on my students and workshop attendees. They pretty much let me know what areas of Flash Application development give them the most trouble or require further explanation then they cannot find in the documentation or on forums, etc. For many developers the Flash platform offers a great opportunity for the rapid application of Rich Internet Applications, but its not without its learning curve, so I look to the areas where I get a lot of questions or in the case of Catalyst, where there is confusion as to what the product produces and how it fits into their current workflow.

I know that you provide people with some courses. Could you tell more about them?

I have been training for well over 15 years and its probably what I enjoy doing the most. So if Im not developing, Im teaching. I teach just about everything in the Adobe product line as well as languages like JavaScript, HTML, XML, XSLT, that sort of thing. The

48

07/2011 (25)

demand for Flex/Flash classes has been dominating my time for the past year and half to two years. I basically get inquries for training, and then go visit the company to conduct anywhere from one to five days of training. Budgets are tight and travel can be prohibitive for many companies, so I also conduct a lot of virtual training. These sessions are conducted online using collaboration software like WebEx and while I feel they are not as effective as instructor-led on-site classes, I do enjoy them as well.

What are your plans for the future?

Continuing to do what I love...provide the best and most effective training possible that allows companies to realize a measurable gain in productivity...write articles...and code, though not necessarily in that order.

Could you tell us how did you got started with Flash and Flex?
Ive been a Flash developer since version one. Shortly after Future Splash and used it on and off ever since. Flex was just a natural progression to follow. Prior to the use of Flash I was deeply entrenched in the print world using programs like Quark Xpress, Adobe Pagemaker Adobe Acrobat and eventually Adobe InDesign. I actually started my print career as a typesetter using now antiquated machines and even set hot metal type. Like everyone at the time I became fascinated with web development and began migrating from print work to web work. Flash was one of the many great expressive tools in that arena.

Please tell our readers, in your opinion, what development opportunities of the Flash/Flex world would be?

Well, the Flash-based linked-in groups that I belong to are ripe with job opportunities for Flash and Flex developers. You see the same thing on Dice.com, etc. There was even a recent Wall Street Journal articles citing the shortage of Flash developers. Whether or not the platform dominates the mobile or multiscreen development area, I dont know, but you can be sure Adobe will always be at the forefront of Web Development tools and technologies. That might be HTML5, CSS3 and Jquery or it might be AIR on the desktop, cell phone, tablet, Television, etc. Having said that, if you are a new programmer, learning ActionScript 3 is a great skill that ports to many areas.

07/2011 (25)

TOOLS

Tanida Demo builder 8


D
emo builder is a special screen capture software, which compresses, edits, and adds tags of the captured video, and then exports it as an interactive flash video with lot of options and settings. The most unique feature among screen capture softwares is that you can instantly edit the captured video, and highlight the important information, this is what makes it the best tool for capturing tutorials, presenting your software, or making e-learning material. a video, or a game. The capture is fast and smooth, it didnt slow down my old Pentium computer, and thats a very good point for the software, because the competition of this software did. You can easily select the screen area and size to capture, and when you are ready to shoot, simply starts your capture with a click, or by pressing F1, and the same goes for stopping the capture. You are also able to automatically highlight clicks, and to show the mouses trail.

Capture your screen

There are two capture methods, one is the classic video capture, and the other captures only screenshots, where you can select to capture automatically, or to capture whenever you want it, by pressing a button. If you stay with video capture, the frame rate can be set up to 20 fps, what is satisfying in most cases, but I personally favour the 24, or even the 30 fps option. If you choose lower capture rate, the program will automatically interpolate the mouse movement, so the video will be lighter, but the user wont see a difference with most of the records, unless youre trying to capture

Edit, Caption, Highlight

When youre done with capturing, you can start editing, and tagging captions, highlighting, and adding eye-candies to the video. You can even add more scenes, allowing you to create a welcome screen, and so much more. Surprisingly (if you selected a check box) most of the tagging is already done, the editor adds the click to notifications automatically, what is a huge adventage of the program. The editor must be familiar to any flash developer; there is a timeline, layers, and controls. However it is easy to learn for anyone who wishes to use the program. There are lots of examples bundled with the program, and the controls are really common to use. If you want, you can even add interactivity to the program, with

Figure 1. Setting the screen capture options

Figure 2. The timeline is as good as in a professional video-editing tool

Figure 3. The annoying 3D view

50

07/2011 (25)

Tanida Demo builder 8

(exe), video (mp4, avi, wmv), word document, and pictures (bmp, jpeg, ) If you choose flash, you can add or remove the video control bar from the export.

Conclusion
Figure 4. You can easily manage scenes

simple go to scene command, or code anything in JavaScript. The editor allows you to rotate the screen in 3D plane, what is a great option to have, but Id never use it, because the presentation can really become a bad clich with it, and it doesnt help users to see what you meant to show. However the zoom function is very handy and it is a great feature to help the viewers. The editor lets you to voice-over the video, so you can explain whats happening on the screen, and you add narration to the interactive sections as well.

All-in-all I really liked this program, because it is simple, easy to learn, and professional. I would really recommend it to capture quality user-manuals for any apps and websites you develop, but it can be used for many other reasons, even if you want to only record the screen, and not to add anything else, Demo Builder is a great solution, because of the easy use, and good performance. Unfortunately it is only available for Windows, so Mac users have to go on without this great tool. You can get the 1 user license for $199, what is pretty expensive, but it is certainly the best in its category, so if you really want to create quality captures, its worth the price.

Export

When youre satisfied with the edited video, you have several export options: flash (html + swf), standalone
a d v e r t

CSOMK GBOR
i s e m e n t