May 28, 2011
Posted on May 28, 2011 in Hints and Tips | 1 comment
In this tutorial, we’ll learn how to use AS3 to create an RIA that can modify the color properties of an image, such as Brightness, Contrast, Hue and Saturation. Read on!
Final Result Preview
Let’s take a look at the final result we will be working towards:
Step 1: Brief Overview
We will use a native ActionScript Class that will get new values from a Slider Component and then apply them to the target image using the ColorMatrixFilter class.
Step 2: Flash Document Settings
Launch Flash and create a new document. Set the stage size to 557x400px, and the frame rate to 24fps.
Step 3: The Interface
The interface will be very simple; just an image in the stage that will be then modified by the Sliders Components in the Adjust Color Panel.
Step 4: Demo Image
We’ll need an image to test our application, choose it from your personal collection or download one for testing.
This is the image from the demo, obtained from Flickr, with a Creative Commons License.
Step 5: Instance Names
Create a panel and four Sliders with instance names as seen in the following image:
You can add bars above the Sliders as shown to improve the appearance.
Step 6: Slider Values
Let’s set the Slider components’ values.
These are obtained from the minimum and maximum valid values of the AdjustColor class, which we will use to adjust each property:
- brightSL: -100 to 100
- contSL: -100 to 100
- hueSL: -180 to 180
- satSL: -100 to 100
Step 7: New ActionScript Class
Create a new ActionScript 3.0 Class (Cmd + N) and save it as Main.as in your class folder.
Step 8: Class Structure
Create your basic class structure to begin writing your code.
>
package
{
import flash.display.Sprite;
public class Main extends Sprite
{
public function Main():void
{
// constructor code
}
}
}
Step 9: Required Classes
These are the classes we’ll need to import for our class to work; the import directive makes externally defined classes and packages available to your code.
import flash.display.Sprite;
import fl.motion.AdjustColor;
import flash.filters.ColorMatrixFilter;
import fl.events.SliderEvent;
Step 10: Variables
These are the variables we’ll use; read the comments in the code to learn more about them.
private var color:AdjustColor = new AdjustColor(); //This object will hold the color properties
private var filter:ColorMatrixFilter; //Will store the modified color filter to change the image
Step 11: Constructor
The constructor is a function that runs when an object is created from a class; this code is the first to execute when you make an instance of an object, or in this case it is run when the SWF is loaded, as it is in the document class.
It will perform the neccesary actions to start the application.
public final function Main():void
{
//Code
}
Step 12: Initial Matrix
The color matrix will be generated by the values stored in the AdjustColor properties; we need to set initial values to these properties in order to get a correct matrix. If we don’t do this, an array with null values will be generated.
/* Required to create initial Matrix */
color.brightness = 0;
color.contrast = 0;
color.hue = 0;
color.saturation = 0;
/* This function will add the necessary event listeners */
addListeners();
Step 13: Add Slider Listeners
This function adds listeners to the Slider components in order to call certain functions whenever their values change.
private final function addListeners():void
{
colorPanel.brightSL.addEventListener(SliderEvent.CHANGE, adjustBrightness);
colorPanel.contSL.addEventListener(SliderEvent.CHANGE, adjustContrast);
colorPanel.hueSL.addEventListener(SliderEvent.CHANGE, adjustHue);
colorPanel.satSL.addEventListener(SliderEvent.CHANGE, adjustSaturation);
}
Step 14: Brightness
This function modifies the Brightness value, getting its data from the brightSL slider component.
private final function adjustBrightness(e:SliderEvent):void
{
color.brightness = e.target.value;
update();
}
Step 15: Contrast
This function modifies the Contrast value, getting its data from the contSL slider component.
private final function adjustContrast(e:SliderEvent):void
{
color.contrast = e.target.value;
update();
}
Step 16: Hue
This function modifies the Hue value, getting its data from the hueSL slider component.
private final function adjustHue(e:SliderEvent):void
{
color.hue = e.target.value;
update();
}
When you modify the hue of a color, you move it around the color wheel by the specified number of degrees.
Step 17: Saturation
This function modifies the Saturation value, getting its data from the satSL slider component.
private final function adjustSaturation(e:SliderEvent):void
{
color.saturation = e.target.value;
update();
}
When you modify the saturation of a color, you move it towards or away from the center of the color wheel.
Step 18: Update Function
This function is called in every slider change. It renews the ColorMatrixFilter value and applies it to the image in stage.
private final function update():void
{
filter = new ColorMatrixFilter(color.CalculateFinalFlatArray());
image.filters = [filter];
}
Step 19: Set Main Class
We’ll make use of the Document Class in this tutorial, if you don’t know how to use it or are a bit confused please read this QuickTip.
Step 20: Test
You’re ready to test — press Cmd+Return to export your application and see it working!
Conclusion
You’ve learned an excellent technique of image manipulation, experiment with it!
Thanks for reading this tutorial, I hope you’ve found it useful!
More Colorful Resources on Activetuts+



View full post on Activetuts+
May 9, 2011
Posted on May 9, 2011 in Hints and Tips | 3 comments
In this tutorial, we’ll learn how to implement native multitouch gestures to use in your applications. Read on!
Final Result Preview
Let’s take a look at the final result we will be working towards:
Note: This example will work only on Multitouch devices (Tablets, Smartphones, Touch Screen Computers and Multitouch trackpads under AIR).
Note for Android users: Multitouch won’t run in the SWF embedded in an HTML page in an Android browser, but the Source download does include an APK you can use to check it out. (Please note that the APK is just for the purpose of a quick demonstration of the gestures themselves, and does not display entirely correctly.)
You can pinch to zoom, spin to rotate, and swipe to change the image. Check out the video demo if you’re unable to test the preview on your device:
Step 1: Brief Overview
We’ll use the native Multitouch support built in to the Flash Player to create a gesture-based image application.
Step 2: Flash Document Settings
Launch Flash and create a new document. Set the stage size to 600x300px, and the frame rate to 24fps.
Step 3: Interface
The interface will be very simple, just an image in the stage that will be then modified by the gestures.
Step 4: Get Some Images
We’ll need some images to test our application, choose them from your personal collection or download a few for testing.
These are the images from the demo, obtained from Flickr, all with a Creative Commons License.
Grass 01 by 100kr
deep impact on planet color by spettacolopuro
Yosemite : fall colours by tibchris
Flower by Antonio Manchado
Step 5: Export For ActionScript
Convert one of the images to a movie clip, and add the rest of the images to that clip in different frames. Name the clip SlideItem and mark the Export for ActionScript box.
Step 6: TweenNano
We’ll use a different tween engine from the default included in Flash, this will increase performance as well as being easier to use.
You can download TweenNano from its official website.
Step 7: New ActionScript Class
Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.
Step 8: Class Structure
Create your basic class structure to begin writing your code.
package
{
import flash.display.Sprite;
public class Main extends Sprite
{
public function Main():void
{
// constructor code
}
}
}
Step 9: Required Classes
These are the classes we’ll need to import for our class to work, the import directive makes externally defined classes and packages available to your code.
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.events.TransformGestureEvent;
import com.greensock.TweenNano;
import com.greensock.easing.Strong;
Step 10: Variables
These are the variables we’ll use, read the comments in the code to find out more about them.
private var slideItem:SlideItem; //The object that will be affected by the gestures
private var tempContainer:Sprite; //An empty sprite that will store the slide item
Step 11: Constructor
The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object or runs using the Document Class.
It performs the necessary actions to start the application.
public final function Main():void
{
//Code
}
Step 12: Enable Gestures Input
This line tells the Flash Player to identify the multi-touch mode for touch and gesture event handling.
Multitouch.inputMode = MultitouchInputMode.GESTURE;
Read more about this on help.adobe.com.
Step 13: Slide Item
Let’s instantiate the images that will respond to the gesture events.
slideItem = new SlideItem();
/* Prevents the image from changing */
slideItem.stop();
/* Center the image */
slideItem.x = stage.stageWidth * 0.5;
slideItem.y = stage.stageHeight * 0.5;
addChild(slideItem);
listeners('add', slideItem); //see next step
Step 14: Add Listeners
This function adds or removes the gesture listeners depending on the specified parameter.
private final function listeners(action:String, target:Sprite):void
{
if(action == 'add')
{
target.addEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoom);
target.addEventListener(TransformGestureEvent.GESTURE_ROTATE, onRotate);
target.addEventListener(TransformGestureEvent.GESTURE_PAN, onPan);
target.addEventListener(TransformGestureEvent.GESTURE_SWIPE, onSwipe);
}
else
{
target.removeEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoom);
target.removeEventListener(TransformGestureEvent.GESTURE_ROTATE, onRotate);
target.removeEventListener(TransformGestureEvent.GESTURE_PAN, onPan);
target.removeEventListener(TransformGestureEvent.GESTURE_SWIPE, onSwipe);
}
}
This means that the listeners() function called in the previous step will add event listeners to the sliding image, to make it listen for zooming, panning, rotating, and swiping gestures.
Step 15: Pinch to Zoom
This function responds to the well known pinch gesture. It handles the image zoom in and zoom out.
private final function onZoom(e:TransformGestureEvent):void
{
/* Use the event data to scale the target image */
e.target.scaleX *= e.scaleX;
e.target.scaleY *= e.scaleY;
}
Step 16: Spin to Rotate
Rotation is handled by this function, two fingers are used to spin the image in the stage.
private final function onRotate(e:TransformGestureEvent):void
{
/* Use the event data to rotate the target image */
e.target.rotation += e.rotation;
}
Step 17: Slide to Pan
The Pan function is used to move the image to see parts that are off-stage.
private final function onPan(e:TransformGestureEvent):void
{
e.target.x += e.offsetX;
e.target.y += e.offsetY;
}
Step 18: Swipe to Swap
This function is a little bigger due to the four swipe directions available. The gesture is similar to that from the previous step, but firmer, and instead of simply moving the image around, it swaps it for a different image.
It first checks if a previous item is on the stage and stores it in a container in order to tween it and be able to remove it later. Then, the offset property is read to determine the direction of the swipe, showing the corresponding animation and image.
private final function onSwipe(e:TransformGestureEvent):void
{
/* Check if image is on stage */
if(slideItem != null)
{
tempContainer = new Sprite();
tempContainer.addChild(slideItem);
addChild(tempContainer);
}
/* Change Images */
if(e.offsetX == 1)
{
//right
slideItem = new SlideItem();
slideItem.gotoAndStop(1);
slideItem.x = -slideItem.width;
slideItem.y = stage.stageHeight * 0.5;
listeners('add', slideItem);
addChild(slideItem);
TweenNano.to(tempContainer, 0.5, {x:stage.stageWidth, onComplete: removeLast});
TweenNano.to(slideItem, 0.5, {x:stage.stageWidth * 0.5});
}
if(e.offsetX == -1)
{
//left
slideItem = new SlideItem();
slideItem.gotoAndStop(2);
slideItem.x = stage.stageWidth + slideItem.width;
slideItem.y = stage.stageHeight * 0.5;
listeners('add', slideItem);
addChild(slideItem);
TweenNano.to(tempContainer, 0.5, {x:-slideItem.width, onComplete: removeLast});
TweenNano.to(slideItem, 0.5, {x:stage.stageWidth * 0.5});
}
if(e.offsetY == -1)
{
//up
slideItem = new SlideItem();
slideItem.gotoAndStop(3);
slideItem.x = stage.stageWidth * 0.5;
slideItem.y = stage.stageHeight + slideItem.height;
listeners('add', slideItem);
addChild(slideItem);
TweenNano.to(tempContainer, 0.5, {y:-slideItem.height, onComplete: removeLast});
TweenNano.to(slideItem, 0.5, {y:stage.stageHeight * 0.5});
}
if(e.offsetY == 1)
{
//down
slideItem = new SlideItem();
slideItem.gotoAndStop(4);
slideItem.x = stage.stageWidth * 0.5;
slideItem.y = -slideItem.height;
listeners('add', slideItem);
addChild(slideItem);
TweenNano.to(tempContainer, 0.5, {y:slideItem.height, onComplete: removeLast});
TweenNano.to(slideItem, 0.5, {y:stage.stageHeight * 0.5});
}
}
Step 19: Remove Last Slide Item
When the animation is finished, the item offstage is destroyed to save memory.
private final function removeLast():void
{
listeners('remove', tempContainer.getChildAt(0) as Sprite);
removeChild(tempContainer);
tempContainer = null;
}
Step 20: Set Main Class
We’ll make use of the Document Class in this tutorial, if you don’t know how to use it or are a bit confused please read this Quick Tip.
Conclusion
Gestures add a nice touch and and offer great interaction in your application, use them!
Thanks for reading this tutorial, I hope you’ve found it useful!



View full post on Activetuts+
Apr 8, 2011
Posted on Apr 8, 2011 in Hints and Tips | 1 comment
If you are involved with AS3 development you might have heard of a virtual machine that lives inside the Flash Player or of the so-called bytecode that your code gets transformed into. But what are they exactly?
A significant part of the Flash Player is the AVM – the ActionScript Virtual Machine. When you compile your AS3 code it gets transformed into a binary instruction set, called bytecode, which is embedded into the produced SWF. As a user loads the SWF into the Flash Player, the AVM parses the bytecode and executes it step by step.
Let’s examine the process in a little bit more detail: Have a look at the following statement and imagine we want to execute it (compute the result and assign it to “foo”):
foo = 2 + 3 * 4;
From a human’s point of view this line means “Multiply 3 by 4, add 2 to the result and assign that to a variable named foo”.
On the other hand if a computer reads this line it would store it as “character f, followed by character o, followed by character o, followed by character space, followed by character equals, followed by….” And so on. At this state this information is pretty useless and additional steps need to be taken in order to turn the statement into something that a machine can execute. Basically what we need to do is to compile the source code.
The Compiler
As I noted before, the statement above is raw source code, a collection of characters that mean nothing to a computer. In order to obtain useful information we have to run the code through a few procedures. First, we should turn the stream of characters into words and second, turn the words into sentences.
The first step of turning the characters into words is done by a tokenizer which basically performs lexical analysis of the source code. It runs over the characters and groups them into series of “tokens” (and it also determines their type – identifiers, operators, constants…). After the tokenizer (it’s also called a lexer BTW) finishes its job, we get an array which can be illustrated like this:
[Identifier foo][Operator equals][Integer 2][Operator plus][Integer 3][Operator multiply][Integer 4]
This is a higher level structure that contains “words” instead of the raw characters.
The resulting tokens are fed into a parser. It performs semantic analysis of the tokens and assembles them into machine instructions. In simpler words, it constructs sentences out of the words (tokens) and makes sense out of them (i.e. compiles instructions out of them). For instance if the parser is given a statement 2 + 3; i++; as tokens the parser must first separate the tokens into “sentences” (2 + 3 and i++) and then actually understand them (the first is add operation and second is an increment). After we understand the instruction we can actually compile instructions to the machine out of the input.
After the parsing the tokens of our string we get the following instructions:
push 2
push 3
push 4
multiply
add
assign "foo"
These are instructions that a computer can execute. Compress it to a binary format and you’ve got bytecode. Bytecode is a list of instructions that a machine is very good at processing and when processed in order yield the desired results.
The Interpreter
After we compiled the source code to bytecode we can execute it with a virtual machine. The VM is software that executes the bytecode one instruction at a time, so let’s just walk through the interpretation of our statement:
push 2 — The command is to push the number 2 into the stack. The VM maintains a stack during execution which the commands can operate on, that is to push into and pop off values (http://en.wikipedia.org/wiki/Stack_(data_structure)). Currently the stack looks like this : [2]
push 3 — push another integer into the stack. Now it looks like [2, 3];
push 4 — push yet another integer into the stack. Now it looks like [2, 3, 4];
multiply — this command pops 2 values off the stack, multiplies them and pushes the result back to the stack. It pops the values 3 and 4 (which are currently on the top of the stack), multiplies them and pushes the resulting 12 to the stack. It affects the stack to look like [2, 12];
add — you’ve probably guessed it: The command pop 12 and 2 off the stack, adds them and pushes the resulting 14 into the stack. Now only 14 remains inside the stack.
assign "foo" — This command pops a value off the stack and assign it to a variable named foo. So now the variable foo contains value of 14 and the stack is empty.
That’s it! This is an example of an extremely simple statement executed of an extremely simple virtual machine. Let’s examine a slightly more complicated example:
bar = 12 / (4 + 2) - (6 - 9) * 3
This may compile to (I say “may” because there are different ways to compile the statement):
push 12
push 4
push 2
add
divide
push 6
push 9
subtract
push 3
multiply
subtract
assign "bar"
This will be interpreted like:
- The first 3 pushes will be added to the stack: [12, 4, 2]
add — will sum the 2 values at the top of the stack: [12, 6]
divide — will pop 6, then pop 12, divide 12 by 6 and push the result to the stack: [2]
- The next 2 commands will push integers into the stack: [2, 6, 9]
subtract — will subtract the 2 numbers at the top of the stack. Will pop 9, then 6, then subtract 6 from 9 and push the result to the stack: [2, -3]
- Another integer will be pushed to the stack: [2, -3, 3]
multiply — will pop and multiply the 2 numbers at the top of the stack. -9, which is 3 times -3, will be pushed back to the stack: [2, -9]
subtract — will subtract -9 from 2 and push the result to the stack: [11]
assign — will pop 11 and assign it to a variable named “bar”. Stack is now empty.
The result is now stored inside a variable named “bar” and it is 11. Yay!
Conclusion
That’s the most basic information about a VM, it might come in handy when you start learning some low-level Flash Player stuff. The VM inside the Flash Player is of course much more complex but the base is the same as in the example presented above.
If you want to learn more about the ActionScript Virtual Machine you can take a look at this PDF document by Adobe. Thanks for reading!



View full post on Activetuts+
Jan 20, 2011
Posted on Jan 20, 2011 in Hints and Tips | 0 comments
Dive into this Quick Tip and discover how to change the Frame Rate of your movie, while it’s running…
Final Result Preview
Let’s take a look at the final result we will be working towards:
Step 1: Brief Overview
We’ll make use of a Slider component to modify the stage framerate property and display a MovieClip to see the changes.
Step 2: Set Up Your Flash File
Launch Flash and create a new Flash Document, set the stage size to 400x200px and the frame rate to 25fps.
Step 3: Interface
This is the interface we’ll be using, it includes a Slider Component and a MovieClip taken from my Apple Preloader tutorial.
You’ll also notice some static text below the slider indicating the minimum and maximum FPS.
Step 4: Slider
Open the Components Panel (Cmd+F7) and drag the Slider component from the User Interface folder, align it to the center in the stage and click the Properties Panel to edit its parameters.
Use the data from the image above and prepare for some ActionScript 3…
Step 5: ActionScript
Create a new ActionScript Class (Cmd+N), save the file as Main.as and start writing:
package
{
import flash.display.Sprite;
import fl.events.SliderEvent;
public class Main extends Sprite
{
public function Main():void
{
//Listen for slider movement
slider.addEventListener(SliderEvent.CHANGE, changeFPS);
}
private function changeFPS(e:SliderEvent):void
{
//Change the frame rate using the slider value
stage.frameRate = e.value;
}
}
}
Step 6: Document Class
Remember to add the class name to the Class field in the Publish section of the Properties panel.
Conclusion
Try the demo and experiment with the uses of this feature!
I hope you liked this Quick Tip, thank you for reading!



View full post on Activetuts+