Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This tutorial was first published in July, 2009.
A fluid web layout uses 100% width (and height) of the browser, floating all the contained elements into certain positions. This is opposed to fix-width layout where contents remain fixed no matter what the browser size is.
This technique is popular in HTML/CSS websites, but this tut will show you how to create a similar fluid layout effect in Flash. Every element will reposition itself with ease animation when the browser resizes.
Introduction
During the following steps we’ll create ActionScript 3 classes which make our flash website fluid. All our display symbols will retain their alignment when the Flash is resized.
The ActionScript classes created in this tutorial can be easily reused in different projects.
Step 1: Background Information
As shown in the image below, all the elements which float according to the browser size will be referred to as "fluid objects".
Step 2: Fluid Object Coordinates
Each fluid object will contain alignment parameters. The parameters store the x, y, x offset, y offset value of the object to indicate how it aligns.
Assigning x and y to 0 will make the fluid object align to the top left corner. Assigning x and y to 1 will make the fluid object align to the bottom right corner. Therefore, assigning x and y value between 0 and 1 will float the object at a percentage of the width and height of the browser.
The offset X and Y offset the position of the fluid objects while they align. Offsetting useful when positioning an object whose alignment point is not at the center. The offset is also useful for making margins on the alignment.
Step 3: Create a Directory
Create a directory called "FluidLayout" in the working directory. This directory will store all classes which relate to the fluid layout classes.
It’s a good habit to put the ActionScript class files in directories by category. For example, fluid layout classes will be placed in the "FluidLayout" folder in this case.
Please note that all the directory names, file names and codes are case sensitive.
Step 4: New ActionScript File
Open a new ActionScript file named "FluidObject.as". Save this ActionScript file into the "FluidLayout" directory.
The class FluidObject will store the alignment parameters of the symbols and reposition the symbols when the browser resizes.
Step 5: The Class Skeleton
Let’s start coding the FluidObject.as now.
package FluidLayout {
/* Add import classes here */
public class FluidObject {
/* Declare instance variables here */
/* Constructor of the class */
public function FluidObject(target:DisplayObject,paramObj:Object)
{
}
/* Function that repositions the monitored object */
protected function reposition():void
{
}
/* Function that is called when the RESIZE event is fired */
protected function onStageResize(e):void
{
}
}
}
Step 6: Importing Required Classes
Add the following code where you see: /* Add import classes here */
/* class needed on resize Event */
import flash.events.Event;
/* classes needed for MovieClip and DisplayObject */
import flash.display.*;
Step 7: Declaring Instance Variables
There are three instance variables for this class:
“_param” will store the alignment parameters.
“_target” will point to the monitored symbol.
“_stage” is a copy instance of the flash stage.
There is also a setter for “_param” to enable changing of the alignment parameters. Add the following code where you see: /* Declare instance variables here */
/* alignment parameters */
protected var _param:Object;
/* target object to be monitored */
protected var _target:DisplayObject;
/* stage instance of the flash document */
protected var _stage:Stage;
/* Setter for the alignment param */
public function set param(value:Object):void {
_param = value;
this.reposition();
}
Step 8: Implementing the Constructor
The constructor will initialize the target monitored symbol and store the given alignment parameters.
/* Constructor of the class */
public function FluidObject(target:DisplayObject,paramObj:Object)
{
/* Assign the instance variables */
_target = target;
_param = paramObj;
_stage = target.stage;
/* add event handler for stage resize */
_stage.addEventListener(Event.RESIZE, onStageResize);
/* reposition the object with the alignment setting applied*/
this.reposition();
}
Step 9: Implementing reposition()
The repositioning function is in charge of calculating the new x/y position of the monitored fluid object.
/* Function that reposition the monitored object */
protected function reposition():void
{
/* get the current width and height of the flash document */
var stageW = _stage.stageWidth;
var stageH = _stage.stageHeight;
/* update the x and y value of the monitored object */
_target.x = (stageW * _param.x) + _param.offsetX;
_target.y = (stageH * _param.y) + _param.offsetY;
}
Step 10: Implementing onStageResize()
The onStageResize function is an event handler which is called when the browser resizes.
/* Function that is called when the RESIZE event is fired */
protected function onStageResize(e):void
{
/* reposition the target */
this.reposition();
}
Step 11: The Completed Class
The finished class FluidObject is finished in this step.
package FluidLayout {
/* class needed on resize Event */
import flash.events.Event;
/* classes needed for MovieClip and DisplayObject */
import flash.display.*;
public class FluidObject {
/* alignment parameters */
protected var _param:Object;
/* target object to be monitored */
protected var _target:DisplayObject;
/* stage instance of the flash document */
protected var _stage:Stage;
/* Setter for the alignment param */
public function set param(value:Object):void {
_param=value;
this.reposition();
}
/* Constructor of the class */
public function FluidObject(target:DisplayObject,paramObj:Object)
{
/* Assign the instance variables */
_target = target;
_param = paramObj;
_stage = target.stage;
/* add event handler for stage resize */
_stage.addEventListener(Event.RESIZE, onStageResize);
/* reposition the object with the alignment setting applied*/
this.reposition();
}
/* Function that repositions the monitored object */
protected function reposition():void
{
/* get the current width and height of the flash document */
var stageW = _stage.stageWidth;
var stageH = _stage.stageHeight;
/* update the x and y value of the monitored object */
_target.x = (stageW * _param.x) + _param.offsetX;
_target.y = (stageH * _param.y) + _param.offsetY;
}
/* Function that is called when the RESIZE event is fired */
protected function onStageResize(e):void
{
/* reposition the target */
this.reposition();
}
}
}
Step 12: Time to Create a Flash File
Begin a new Flash Document with ActionScript 3.0 supported and call it "website.fla". Then set the Document class as "Website".
If a dialog box pops up with the message: "A definition for the document class could not be found in the classpath,…" just click "OK" to bypass it. We’re going to create that class after drawing the graphic symbols.
The background image will be dark in this tutorial (I’ve put together my own space-like image using Photoshop). Therefore the background color of the flash document needs to set to black. Click Modify > Document to open the Document Properties dialog and change the background color.
Step 13: Draw the Title Symbol
There will be 5 flash symbols on the stage:
background
title
menu
middle content
footer
Let’s make the title first. The aim of this tutorial is to create floating symbols in the fluid layout rather then creating fancy website components. The symbols will only contain a text field indicating the purpose only.
For the title symbol, there’s a semi-transparent background. In order to fit different widths of the browser, the width of the background need to be large enough.
After having finished drawing the symbol, click Modify > Convert to Symbol (F8). Click the "Advanced" button to show detailed settings for the symbol.
Click "Export for ActionScript" to enable the ActionScript to access this symbol. Then find the "Class" field in the dialog and set the value to "Title" for the title symbol. This means that we’ve assigned a new Class called "Title" to this symbol. We can use this symbol later in the ActionScript.
Remember to name your symbol for easy recognition before you click OK. If a dialog box pops up with the message "A definition for this class could not be found in the classpath,…" again, just click "OK" to bypass it. Since we’ll not add any behavior to the symbol, we’ll let Flash create an empty class for us.
Step 14: Draw the Other Symbols
Delete the "title" symbol instance on stage because it will be created by ActionScript later.
We’ll use the same method to draw "background", "menu", "middle content" and "footer". The class name of these symbols will be Background, Menu, Middle and Footer accordingly.
The background image can be downloaded from the source files. Other symbols are text-field only.
Step 15: Code the Document Class
Create an ActionScript file and named as "Website.as"; this class file should be saved in the same directory as the website.fla file.
This class must also share the same name as that set in the Document Class (refer to Step 12). For example, the Document Class "Website" refers to "Website.as" in the same directory. This ActionScript class will be loaded right after the flash is loaded.
Here is the skeleton of the Document Class:
package {
import flash.display.*;
import FluidLayout.*;
public class Website extends MovieClip{
public function Website()
{
}
}
}
Step 16: Implementing the Constructor
package {
import flash.display.*;
import FluidLayout.*;
public class Website extends MovieClip{
public function Website()
{
/* Set the Scale Mode of the Stage */
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
/* Add the symbols to stage */
var bg = new Background();
addChild(bg);
var title = new Title();
addChild(title);
var menu = new Menu();
addChild(menu);
var middle = new Middle();
addChild(middle);
var footer = new Footer();
addChild(footer);
/* Apply the alignment to the background */
var bgParam = {
x:0,
y:0,
offsetX: 0,
offsetY: 0
}
new FluidObject(bg,bgParam);
/* Apply the alignment to the title */
var titleParam = {
x:0,
y:0,
offsetX:0,
offsetY:0
}
new FluidObject(title,titleParam);
/* Apply the alignment to the menu */
var menuParam = {
x:1,
y:0,
offsetX: -menu.width - 20,
offsetY: 20
}
new FluidObject(menu,menuParam);
/* Apply the alignment to the content */
var middleParam = {
x:0.5,
y:0.5,
offsetX: -middle.width/2,
offsetY: -middle.height/2
}
new FluidObject(middle,middleParam);
/* Apply the alignment to the footer */
var footerParam = {
x:1,
y:1,
offsetX: -footer.width - 10,
offsetY: -footer.height -10
}
new FluidObject(footer,footerParam);
}
}
}
Step 17: Ensure All Assets are Ready
Open website.fla in Flash and check again before texting the movie.
There’s no need to place the symbols on the stage because the Website.as will create symbol instances from library by using their class names. The linkage class names of the symbols needs to be correct in order for the script to use them. The linkage class name can be checked in the library panel.
Step 18: Ready to View the Result
Click Control > Text Movie or Ctrl(Cmd) + Enter to test the flash website.
Try resizing the window and check if all objects are repositioning to the correct alignment.
Step 19: Further Work
Each FluidObject now needs to have specific x,y,offsetX and offsetY property values. A new Class will be created in the coming steps to simplify the future code when adding new fluid objects.
Step 20: SimpleFluidObject Class
Open a new ActionScript file named "SimpleFluidObject.as". Save this file inside the "FluidLayout" directory because this is part of the FluidLayout package.
This file extends FluidObject class so that it will provides simple alignment by using names like TOP, MIDDLE, BOTTOM_RIGHT instead of specifying the x,y properties.
Here is the skeleton of the class:
package FluidLayout {
import flash.events.Event;
import flash.display.*;
public class SimpleFluidObject extends FluidObject{
public function SimpleFluidObject(target:DisplayObject,paramObj:Object)
{
}
}
}
Step 21: Implementing the Constructor
package FluidLayout {
import flash.events.Event;
import flash.display.*;
public class SimpleFluidObject extends FluidObject{
public function SimpleFluidObject(target:DisplayObject,paramObj:Object)
{
/* Tell parent class to init the constructor */
super(target,paramObj);
/* assign alignment and margin value by the constructor parameters */
var alignment = paramObj.alignment;
var margin = paramObj.margin;
/* Preset the alignment and margin value if need */
if (alignment == undefined) alignment = "MIDDLE";
if (margin == undefined) margin = 0;
/* convert the alignment (eg. "TOP", "BOTTOM_RIGHT") to x, y, offsetX and offsetY */
var params = new Object();
switch (alignment){
case "TOP_LEFT":
params = {
x:0,
y:0,
offsetX: margin,
offsetY: margin
};
break;
case "TOP":
params = {
x:.5,
y:0,
offsetX: -target.width/2,
offsetY: margin
};
break;
case "TOP_RIGHT":
params = {
x:1,
y:0,
offsetX: -target.width - margin,
offsetY: margin
};
break;
case "LEFT":
params = {
x:0,
y:.5,
offsetX: margin,
offsetY: -target.height/2
};
break;
case "MIDDLE":
params = {
x:.5,
y:.5,
offsetX: -target.width/2 - margin/2,
offsetY: -target.height/2 - margin/2
};
break;
case "RIGHT":
params = {
x:1,
y:.5,
offsetX: -target.width - margin,
offsetY: -target.height/2
};
break;
case "BOTTOM_LEFT":
params = {
x:0,
y:1,
offsetX: margin,
offsetY: -target.height - margin
};
break;
case "BOTTOM":
params = {
x:.5,
y:1,
offsetX: -target.width/2,
offsetY: -target.height - margin
};
break;
case "BOTTOM_RIGHT":
params = {
x:1,
y:1,
offsetX: -target.width - margin,
offsetY: -target.height - margin
};
break;
}
_param = params;
/* reposition the fluid object to the right position */
this.reposition();
}
}
}
Step 22: New Usage of the Fluid Objects
Refer to the Website.as file and try using the new alignment method to align the fluid objects.
The Old Method to apply alignment to Title:
/* Apply the alignment to the title */
var titleParam = {
x:0,
y:0,
offsetX:0,
offsetY:0
}
new FluidObject(title,titleParam);
The New Method to apply alignment to Title:
var titleParam = {
alignment: "TOP_LEFT",
margin: 0
}
new SimpleFluidObject(title,titleParam);
Available alignments:
TOP_LEFT, TOP, TOP_RIGHT
LEFT, MIDDLE, RIGHT
BOTTOM_LEFT, BOTTOM, BOTTOM_RIGHT
Step 23: The Published HTML
Now the fluid alignment works on the "Test Movie" in Flash IDE, but there is one key point to make this work on browser.
Open website.fla. Go to File > Publish Settings and ensure HTML is enabled. Click the HTML tab and change the dimension to "Percent". Ensure the percent is set to 100 on both width and height.
Click "Publish" to publish the website as "website.swf" and "website.html" files.
Now open the "website.html" file with your favorite text editor and add the following code in the header. Adding the code right after the </title> tag would be a good choice.
These CSS styles eliminate the gap between the top left side of the HTML and the SWF file.
<style>
body{
margin:0;
padding:0;
}
</style>
Step 24: Advanced Technique Adding Easing
An easing effect can be applied when the browser resizes so that the objects will move to the correct position with an ease out effect.
Open "FluidObject.as". Add the following lines after "import flash.display.*;". These lines will import the tweening animation class to give the code ability to ease the objects.
/* set the duration of the easing animation (seconds) */
var duration = 0.5;
/* declare the new X/Y value */
var newX = _target.x;
var newY = _target.y;
/* calculate the new X value based on the stage Width */
if (_param.x != undefined){
newX = (stageW * _param.x) + _param.offsetX;
}
/* calculate the new Y value based on the stage Height */
if (_param.y != undefined){
newY = (stageH * _param.y) + _param.offsetY;
}
/* Tell flash to tween the target object to the new X/Y position */
new Tween(_target, "x",Strong.easeOut,_target.x,newX,duration,true);
new Tween(_target, "y",Strong.easeOut,_target.y,newY,duration,true);
We’ve just created two classes which are in charge of the floating fluid objects. We also created an example to align different objects on stage by using the classes. This example is only a sample case; you can use your imagination to play with the alignments. For example, a symbol may be interactive and its alignment may change from top to bottom when the user clicks on it.
The file structure should be the same as below after you finish this tutorial. Specifically, the FluidObject.as and SimpleFluidObject.as should be in the "FluidLayout" directory in order to work.
Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This tutorial was first published in July, 2009.
A fluid web layout uses 100% width (and height) of the browser, floating all the contained elements into certain positions. This is opposed to fix-width layout where contents remain fixed no matter what the browser size is.
This technique is popular in HTML/CSS websites, but this tut will show you how to create a similar fluid layout effect in Flash. Every element will reposition itself with ease animation when the browser resizes.
Introduction
During the following steps we’ll create ActionScript 3 classes which make our flash website fluid. All our display symbols will retain their alignment when the Flash is resized.
The ActionScript classes created in this tutorial can be easily reused in different projects.
Step 1: Background Information
As shown in the image below, all the elements which float according to the browser size will be referred to as "fluid objects".
Step 2: Fluid Object Coordinates
Each fluid object will contain alignment parameters. The parameters store the x, y, x offset, y offset value of the object to indicate how it aligns.
Assigning x and y to 0 will make the fluid object align to the top left corner. Assigning x and y to 1 will make the fluid object align to the bottom right corner. Therefore, assigning x and y value between 0 and 1 will float the object at a percentage of the width and height of the browser.
The offset X and Y offset the position of the fluid objects while they align. Offsetting useful when positioning an object whose alignment point is not at the center. The offset is also useful for making margins on the alignment.
Step 3: Create a Directory
Create a directory called "FluidLayout" in the working directory. This directory will store all classes which relate to the fluid layout classes.
It’s a good habit to put the ActionScript class files in directories by category. For example, fluid layout classes will be placed in the "FluidLayout" folder in this case.
Please note that all the directory names, file names and codes are case sensitive.
Step 4: New ActionScript File
Open a new ActionScript file named "FluidObject.as". Save this ActionScript file into the "FluidLayout" directory.
The class FluidObject will store the alignment parameters of the symbols and reposition the symbols when the browser resizes.
Step 5: The Class Skeleton
Let’s start coding the FluidObject.as now.
package FluidLayout {
/* Add import classes here */
public class FluidObject {
/* Declare instance variables here */
/* Constructor of the class */
public function FluidObject(target:DisplayObject,paramObj:Object)
{
}
/* Function that repositions the monitored object */
protected function reposition():void
{
}
/* Function that is called when the RESIZE event is fired */
protected function onStageResize(e):void
{
}
}
}
Step 6: Importing Required Classes
Add the following code where you see: /* Add import classes here */
/* class needed on resize Event */
import flash.events.Event;
/* classes needed for MovieClip and DisplayObject */
import flash.display.*;
Step 7: Declaring Instance Variables
There are three instance variables for this class:
“_param” will store the alignment parameters.
“_target” will point to the monitored symbol.
“_stage” is a copy instance of the flash stage.
There is also a setter for “_param” to enable changing of the alignment parameters. Add the following code where you see: /* Declare instance variables here */
/* alignment parameters */
protected var _param:Object;
/* target object to be monitored */
protected var _target:DisplayObject;
/* stage instance of the flash document */
protected var _stage:Stage;
/* Setter for the alignment param */
public function set param(value:Object):void {
_param = value;
this.reposition();
}
Step 8: Implementing the Constructor
The constructor will initialize the target monitored symbol and store the given alignment parameters.
/* Constructor of the class */
public function FluidObject(target:DisplayObject,paramObj:Object)
{
/* Assign the instance variables */
_target = target;
_param = paramObj;
_stage = target.stage;
/* add event handler for stage resize */
_stage.addEventListener(Event.RESIZE, onStageResize);
/* reposition the object with the alignment setting applied*/
this.reposition();
}
Step 9: Implementing reposition()
The repositioning function is in charge of calculating the new x/y position of the monitored fluid object.
/* Function that reposition the monitored object */
protected function reposition():void
{
/* get the current width and height of the flash document */
var stageW = _stage.stageWidth;
var stageH = _stage.stageHeight;
/* update the x and y value of the monitored object */
_target.x = (stageW * _param.x) + _param.offsetX;
_target.y = (stageH * _param.y) + _param.offsetY;
}
Step 10: Implementing onStageResize()
The onStageResize function is an event handler which is called when the browser resizes.
/* Function that is called when the RESIZE event is fired */
protected function onStageResize(e):void
{
/* reposition the target */
this.reposition();
}
Step 11: The Completed Class
The finished class FluidObject is finished in this step.
package FluidLayout {
/* class needed on resize Event */
import flash.events.Event;
/* classes needed for MovieClip and DisplayObject */
import flash.display.*;
public class FluidObject {
/* alignment parameters */
protected var _param:Object;
/* target object to be monitored */
protected var _target:DisplayObject;
/* stage instance of the flash document */
protected var _stage:Stage;
/* Setter for the alignment param */
public function set param(value:Object):void {
_param=value;
this.reposition();
}
/* Constructor of the class */
public function FluidObject(target:DisplayObject,paramObj:Object)
{
/* Assign the instance variables */
_target = target;
_param = paramObj;
_stage = target.stage;
/* add event handler for stage resize */
_stage.addEventListener(Event.RESIZE, onStageResize);
/* reposition the object with the alignment setting applied*/
this.reposition();
}
/* Function that repositions the monitored object */
protected function reposition():void
{
/* get the current width and height of the flash document */
var stageW = _stage.stageWidth;
var stageH = _stage.stageHeight;
/* update the x and y value of the monitored object */
_target.x = (stageW * _param.x) + _param.offsetX;
_target.y = (stageH * _param.y) + _param.offsetY;
}
/* Function that is called when the RESIZE event is fired */
protected function onStageResize(e):void
{
/* reposition the target */
this.reposition();
}
}
}
Step 12: Time to Create a Flash File
Begin a new Flash Document with ActionScript 3.0 supported and call it "website.fla". Then set the Document class as "Website".
If a dialog box pops up with the message: "A definition for the document class could not be found in the classpath,…" just click "OK" to bypass it. We’re going to create that class after drawing the graphic symbols.
The background image will be dark in this tutorial (I’ve put together my own space-like image using Photoshop). Therefore the background color of the flash document needs to set to black. Click Modify > Document to open the Document Properties dialog and change the background color.
Step 13: Draw the Title Symbol
There will be 5 flash symbols on the stage:
background
title
menu
middle content
footer
Let’s make the title first. The aim of this tutorial is to create floating symbols in the fluid layout rather then creating fancy website components. The symbols will only contain a text field indicating the purpose only.
For the title symbol, there’s a semi-transparent background. In order to fit different widths of the browser, the width of the background need to be large enough.
After having finished drawing the symbol, click Modify > Convert to Symbol (F8). Click the "Advanced" button to show detailed settings for the symbol.
Click "Export for ActionScript" to enable the ActionScript to access this symbol. Then find the "Class" field in the dialog and set the value to "Title" for the title symbol. This means that we’ve assigned a new Class called "Title" to this symbol. We can use this symbol later in the ActionScript.
Remember to name your symbol for easy recognition before you click OK. If a dialog box pops up with the message "A definition for this class could not be found in the classpath,…" again, just click "OK" to bypass it. Since we’ll not add any behavior to the symbol, we’ll let Flash create an empty class for us.
Step 14: Draw the Other Symbols
Delete the "title" symbol instance on stage because it will be created by ActionScript later.
We’ll use the same method to draw "background", "menu", "middle content" and "footer". The class name of these symbols will be Background, Menu, Middle and Footer accordingly.
The background image can be downloaded from the source files. Other symbols are text-field only.
Step 15: Code the Document Class
Create an ActionScript file and named as "Website.as"; this class file should be saved in the same directory as the website.fla file.
This class must also share the same name as that set in the Document Class (refer to Step 12). For example, the Document Class "Website" refers to "Website.as" in the same directory. This ActionScript class will be loaded right after the flash is loaded.
Here is the skeleton of the Document Class:
package {
import flash.display.*;
import FluidLayout.*;
public class Website extends MovieClip{
public function Website()
{
}
}
}
Step 16: Implementing the Constructor
package {
import flash.display.*;
import FluidLayout.*;
public class Website extends MovieClip{
public function Website()
{
/* Set the Scale Mode of the Stage */
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
/* Add the symbols to stage */
var bg = new Background();
addChild(bg);
var title = new Title();
addChild(title);
var menu = new Menu();
addChild(menu);
var middle = new Middle();
addChild(middle);
var footer = new Footer();
addChild(footer);
/* Apply the alignment to the background */
var bgParam = {
x:0,
y:0,
offsetX: 0,
offsetY: 0
}
new FluidObject(bg,bgParam);
/* Apply the alignment to the title */
var titleParam = {
x:0,
y:0,
offsetX:0,
offsetY:0
}
new FluidObject(title,titleParam);
/* Apply the alignment to the menu */
var menuParam = {
x:1,
y:0,
offsetX: -menu.width - 20,
offsetY: 20
}
new FluidObject(menu,menuParam);
/* Apply the alignment to the content */
var middleParam = {
x:0.5,
y:0.5,
offsetX: -middle.width/2,
offsetY: -middle.height/2
}
new FluidObject(middle,middleParam);
/* Apply the alignment to the footer */
var footerParam = {
x:1,
y:1,
offsetX: -footer.width - 10,
offsetY: -footer.height -10
}
new FluidObject(footer,footerParam);
}
}
}
Step 17: Ensure All Assets are Ready
Open website.fla in Flash and check again before texting the movie.
There’s no need to place the symbols on the stage because the Website.as will create symbol instances from library by using their class names. The linkage class names of the symbols needs to be correct in order for the script to use them. The linkage class name can be checked in the library panel.
Step 18: Ready to View the Result
Click Control > Text Movie or Ctrl(Cmd) + Enter to test the flash website.
Try resizing the window and check if all objects are repositioning to the correct alignment.
Step 19: Further Work
Each FluidObject now needs to have specific x,y,offsetX and offsetY property values. A new Class will be created in the coming steps to simplify the future code when adding new fluid objects.
Step 20: SimpleFluidObject Class
Open a new ActionScript file named "SimpleFluidObject.as". Save this file inside the "FluidLayout" directory because this is part of the FluidLayout package.
This file extends FluidObject class so that it will provides simple alignment by using names like TOP, MIDDLE, BOTTOM_RIGHT instead of specifying the x,y properties.
Here is the skeleton of the class:
package FluidLayout {
import flash.events.Event;
import flash.display.*;
public class SimpleFluidObject extends FluidObject{
public function SimpleFluidObject(target:DisplayObject,paramObj:Object)
{
}
}
}
Step 21: Implementing the Constructor
package FluidLayout {
import flash.events.Event;
import flash.display.*;
public class SimpleFluidObject extends FluidObject{
public function SimpleFluidObject(target:DisplayObject,paramObj:Object)
{
/* Tell parent class to init the constructor */
super(target,paramObj);
/* assign alignment and margin value by the constructor parameters */
var alignment = paramObj.alignment;
var margin = paramObj.margin;
/* Preset the alignment and margin value if need */
if (alignment == undefined) alignment = "MIDDLE";
if (margin == undefined) margin = 0;
/* convert the alignment (eg. "TOP", "BOTTOM_RIGHT") to x, y, offsetX and offsetY */
var params = new Object();
switch (alignment){
case "TOP_LEFT":
params = {
x:0,
y:0,
offsetX: margin,
offsetY: margin
};
break;
case "TOP":
params = {
x:.5,
y:0,
offsetX: -target.width/2,
offsetY: margin
};
break;
case "TOP_RIGHT":
params = {
x:1,
y:0,
offsetX: -target.width - margin,
offsetY: margin
};
break;
case "LEFT":
params = {
x:0,
y:.5,
offsetX: margin,
offsetY: -target.height/2
};
break;
case "MIDDLE":
params = {
x:.5,
y:.5,
offsetX: -target.width/2 - margin/2,
offsetY: -target.height/2 - margin/2
};
break;
case "RIGHT":
params = {
x:1,
y:.5,
offsetX: -target.width - margin,
offsetY: -target.height/2
};
break;
case "BOTTOM_LEFT":
params = {
x:0,
y:1,
offsetX: margin,
offsetY: -target.height - margin
};
break;
case "BOTTOM":
params = {
x:.5,
y:1,
offsetX: -target.width/2,
offsetY: -target.height - margin
};
break;
case "BOTTOM_RIGHT":
params = {
x:1,
y:1,
offsetX: -target.width - margin,
offsetY: -target.height - margin
};
break;
}
_param = params;
/* reposition the fluid object to the right position */
this.reposition();
}
}
}
Step 22: New Usage of the Fluid Objects
Refer to the Website.as file and try using the new alignment method to align the fluid objects.
The Old Method to apply alignment to Title:
/* Apply the alignment to the title */
var titleParam = {
x:0,
y:0,
offsetX:0,
offsetY:0
}
new FluidObject(title,titleParam);
The New Method to apply alignment to Title:
var titleParam = {
alignment: "TOP_LEFT",
margin: 0
}
new SimpleFluidObject(title,titleParam);
Available alignments:
TOP_LEFT, TOP, TOP_RIGHT
LEFT, MIDDLE, RIGHT
BOTTOM_LEFT, BOTTOM, BOTTOM_RIGHT
Step 23: The Published HTML
Now the fluid alignment works on the "Test Movie" in Flash IDE, but there is one key point to make this work on browser.
Open website.fla. Go to File > Publish Settings and ensure HTML is enabled. Click the HTML tab and change the dimension to "Percent". Ensure the percent is set to 100 on both width and height.
Click "Publish" to publish the website as "website.swf" and "website.html" files.
Now open the "website.html" file with your favorite text editor and add the following code in the header. Adding the code right after the </title> tag would be a good choice.
These CSS styles eliminate the gap between the top left side of the HTML and the SWF file.
<style>
body{
margin:0;
padding:0;
}
</style>
Step 24: Advanced Technique Adding Easing
An easing effect can be applied when the browser resizes so that the objects will move to the correct position with an ease out effect.
Open "FluidObject.as". Add the following lines after "import flash.display.*;". These lines will import the tweening animation class to give the code ability to ease the objects.
/* set the duration of the easing animation (seconds) */
var duration = 0.5;
/* declare the new X/Y value */
var newX = _target.x;
var newY = _target.y;
/* calculate the new X value based on the stage Width */
if (_param.x != undefined){
newX = (stageW * _param.x) + _param.offsetX;
}
/* calculate the new Y value based on the stage Height */
if (_param.y != undefined){
newY = (stageH * _param.y) + _param.offsetY;
}
/* Tell flash to tween the target object to the new X/Y position */
new Tween(_target, "x",Strong.easeOut,_target.x,newX,duration,true);
new Tween(_target, "y",Strong.easeOut,_target.y,newY,duration,true);
We’ve just created two classes which are in charge of the floating fluid objects. We also created an example to align different objects on stage by using the classes. This example is only a sample case; you can use your imagination to play with the alignments. For example, a symbol may be interactive and its alignment may change from top to bottom when the user clicks on it.
The file structure should be the same as below after you finish this tutorial. Specifically, the FluidObject.as and SimpleFluidObject.as should be in the "FluidLayout" directory in order to work.
In this tutorial, you will build a desktop Flickr image uploader using the AS3/FlickrAPI and exporting the application as an AIR app.
Step 1: Create a New Flex Project
Start out by opening Flex Builder and creating a new project by hitting “File > New > Flex Project”. Go ahead and give your project a name and location. The main thing you need to worry about here is the “Application Type”, make sure that is set to “Desktop (runs in Adobe AIR)”.
Step 2: Download Necessary Libraries
Before we begin programming, we need to download the libraries we’ll need for this project. Those libraries include the corelib by Adobe and of course the Flickr AS3 library
You’ll need to get the latest build of the Flickr AS3 API via SVN because there is a problem with the “upload” function of the released builds that hasn’t been fixed yet.
Step 3: Move Libraries to Project Folder
With your libraries downloaded, we need to move them into our project folder. Unzip the “corelib” and navigate to the “com” folder inside of the “src” folder. Now open your project folder in a new window and open the “src” folder. Drag the “com” folder to your project’s “src” folder.
Inside of the Flickr API folder, you’ll find a similar file structure as the “corelib” folder. Drill down into the “src > com > adobe > webapis” folder and grab the “flickr” folder. Move that folder over to the project folder into this directory “src > com > adobe > webapis”.
Head back to Flex Builder and refresh your Package Explorer. You should now see the libraries you downloaded showing up inside of your project folder.
Step 4: Set Up the User Interface – Part 1
We’ll not only be uploading images to our Flickr account, but the Title, Tags, and a Description as well, so we’ll need the proper fields.
Set your document size to 320×400. Right-click on your Flex Project Folder and select “properties”. Scroll down to the Flex Compiler panel and enter the following code into the “additional compiler arguments” field, “-default-size 320 415“.
Switch to Design view, open the Components panel and drag out an Image component. Make sure to give the Image component an id titled “imagePreview”, set its height to 205 pixels and constrain its proportions to be 10 pixels from the left, right, and top of the view in the Layout panel.
Next, drag out two TextInput components to the stage and stack them on top of one another with a padding of 10 pixels between them constraining them both to 10 pixels from the left and right. Give the first field an ID of “imageTitle” and set the text value to “Image Title”. Give the second field an id of “imageTags” and a text value of “Tags”.
Step 5: Set Up the User Interface – Part 2
So far we have a preview area for our selected image, fields to enter a title and tags for our image. One more piece of data is missing, a description. Go to the Components panel and drag a Text Area component out and place it below the Tags field. Set the height to 70 pixels and constrain the width to 10 pixels from the right and left. Give the Text Area an id of “imageDesc” and text value of “Image Description”.
Now all we need now is a Select button, an Upload button and a progress bar to monitor our upload progress. Go ahead and drag two buttons to the display area and a progress bar. Place the first button 10 pixels from the left and constrain it to that position. Give it an id of “selectBtn” and set its label to “Select”. Place the second button 10 pixels from the right and constrain it to that position as well. Set its id to “uploadBtn” and label it “Upload”. Position the progress bar in the middle of the two buttons and constrain it to the middle of the application. Let’s give it an id of “pBar”.
Your application should look like the image below:
Step 6: Tab Index
Switch to code view inside of Flex Builder and find the input fields you just created. The three fields you’ll need are the “Title”, “Tags” and “Description” fields. Click inside of each one and add this code tabIndex="n", replacing “n” with a sequential number, like so:
First, head on over to Flickr and sign up for an API key.
Flickr will ask you to name your application and give it a description.
Once you fill in the proper information and agree to the to the terms and conditions, click submit and then Flickr will direct you to a screen with your API Key and the Secret Key for your app. Keep the API Key and Secret handy, you’ll need them soon.
Step 8: Create a Class to Connect to Flickr
Now let’s create a new ActionScript Class that will serve as our connection to Flickr. Head back into Flex Builder and create a new ActionScript Class from the File > New menu; name it FlickrConnect.
Go ahead and paste in these “import” commands and I’ll explain their purpose.
package
{
import flash.net.SharedObject;//needed to set system cookies
import flash.net.URLRequest;
import flash.net.navigateToURL;//opens the authorization window in the browser
import mx.controls.Alert;//we'll use two alert windows in our app
import mx.events.CloseEvent;//Detects when the alert window is closed
//Import all the the Flickr API classes to make sure we have everything we need
import com.adobe.webapis.flickr.*;
import com.adobe.webapis.flickr.events.*;
import com.adobe.webapis.flickr.methodgroups.*;
With this class, we’re going to pass Flickr our API key and the app’s secret key and in return we’ll get an authentication token which we’ll store as a cookie on the user’s system. When our app sends the key to Flickr it will open a browser window asking the user to authenticate the application with their Flickr account, once they choose “authorize” and they return to the app they will be be greeted by an alert window asking them to click “OK” once they have authorized the app with Flickr. Doing this will then send off for the security token and set the cookie storing that token locally in order to bypass the authentication process every time the app is opened.
Step 9: Create Flickr Instance and Initialize the Service
public class FlickrConnect
{
public var flickr:FlickrService;
private var frob:String;
private var flickrCookie:SharedObject = SharedObject.getLocal("FlexFlickrUploader");//store Flickr Token in a cookie
public function FlickrConnect()
{
flickr = new FlickrService("xxxxxxxxxxxxxxxxxxxxxxxxxxxx");//enter Flickr API key
flickr.secret = "xxxxxxxxxxxxxxxx";
if(flickrCookie && flickrCookie.data.auth_token)//if cookie AND Auth Token exist, set token
{
flickr.token = flickrCookie.data.auth_token;
}else//if not, get authentication
{
flickr.addEventListener(FlickrResultEvent.AUTH_GET_FROB, getFrobResponse);
flickr.auth.getFrob();
}
}
In the code above we start by declaring 3 variables that we’ll be using in this class. The “flickr” variable is set as public because we’ll reference this object from within the parent application, the other two variables are private because they are specific to this class only.
In the class constructor, initialize the flickr object by setting it equal to a “new FlickrService” and passing in your Flickr API key as a string. Underneath, set the secret key of our newly created service to the key given to you by Flickr when you applied for an API key.
Underneath our declarations, we first check to see if our system cookie exists and if an “authentication token” has been set. If both of those arguments equal true, we go ahead and set the “token” property of our flickr service equal to the authentication token stored in our cookie. If either of those arguments are not true, we continue the process of authenticating the application.
Add and event listener to the flickr service. The type is of “FlickrResultEvent” and we’re listening for “AUTH_GET_FROB”. Enter the function name “getFrobResponse”. Start a new line and execute the “getFrob()” function of the Flickr API.
Frob
Flickr doesn’t define the term “frob” in their API documentation, however a brief explanation is listed below.
A ‘frob’ is just a hex-encoded string that the Flickr servers hand out as part of the authorization process; a more conventional term for it would be a ‘nonce’.
The function getFrob() will send our API key to Flickr and if the key is valid, Flickr will return a string to us. The frob will be passed to another function that will construct a login URL that we’ll direct the user to to login into their Flickr account and give our app permission to upload photos.
private function getFrobResponse(event:FlickrResultEvent):void
{
if(event.success)
{
frob = String(event.data.frob);
var auth_url:String = flickr.getLoginURL(frob, AuthPerm.DELETE);//generates a login URL
navigateToURL(new URLRequest(auth_url), "_blank"); //opens the browser and asks for your verification
Alert.show("Close this window AFTER you login to Flickr", "Flickr Authorization", Alert.OK, null, onCloseAuthWindow);
}
}
Once we get a response back from Flickr with a frob, we check to see if the response returned a “success”. Once it’s determined a frob was returned, we assign the data returned to a String variable, create another String variable that will be the authentication URL, and then use one of the Flickr AS3 API built in functions that will generate our login URL and assign its value to our “auth_url” string.
The next part should be familiar to anyone who’s worked in Flash for a while. Use Flash’s built in “navigateToURL” function to open Flickr in the browser and prompt the user to log in and give permission to our app to access their account. As part of this process we’ll be asking Flickr for “DELETE” permission which is the highest access level an app can have. With that level of access, we’ll be able to upload, edit, add, and delete. This is a bit overkill, but I chose to keep it at this level as a reference for your own projects.
At the same time we’re being directed to Flickr’s login page, our app is generating an alert window. This window will include the message “Close this window AFTER you login to Flickr”. When the user has logged into Flickr and returned to the app, they will hit “OK” which will call another function that will retrieve an access token from Flickr.
Step 11: Get Access Token
public function onCloseAuthWindow(event:CloseEvent):void
{
flickr.addEventListener(FlickrResultEvent.AUTH_GET_TOKEN, getTokenResponse);
flickr.auth.getToken(frob);
}
This function simply asks Flickr for an access token, Flickr will see that our app (as identified by our frob) has been authorized and will return the token.
Step 12: Set Access Token and System Cookie
private function getTokenResponse(event:FlickrResultEvent):void
{
if(event.success)
{
var authResult:AuthResult = AuthResult(event.data.auth);
flickr.token = authResult.token;
flickrCookie.data.auth_token = flickr.token;
flickrCookie.flush();//set cookie on local computer
}
}
The last function in our FlickrConnect class will accept the token sent from Flickr and store it in a system cookie. Start by again checking to make sure the event was successful. If we were successful in retrieving a token from Flickr, create an instance of “AuthResult” and assign it to a variable called “authResult”. Set the value of the variable equaled to the “auth” value of the returned data. Set the “token” property of our FlickrService to the “token” property of our “authResult” variable.
Next, assign a property of “auth_token” to the cookie we created at the beginning of the class (flickrCookie) and equal it to the “flickr.token”. All that is left is to set the cookie on our local computer, we do so by using the “flush()” function of the SharedObject in AS3.
Now that we have a class to connect to Flickr and set our authentication and permissions, we can start coding the main part of our application.
Step 13: Imports and Variables
In our main script, we’ll import three classes; the class we just created, the built in Flex Alert class, and the Upload class of the Flickr AS3 API.
Of the four variables we’re going to need, the first one we need to create is an instance of the FlickrConnect class we just created, name that class “flickrLogin”. Create a variable called “uploader” with an instance of “Upload” and pass in the flickr instance from our FlickrConnect class. Create two more variables, both of the “File” type. One of those variables, we’ll call “file”, the other “fileToOpen”.
import FlickrConnect;
import mx.controls.Alert;
import com.adobe.webapis.flickr.methodgroups.Upload;
private var flickrLogin:FlickrConnect = new FlickrConnect();
private var uploader:Upload = new Upload(flickrLogin.flickr);
private var file:File;
private var fileToOpen:File = File.documentsDirectory;
Step 14: Initialize and Image Select Function
Now that we have our imports and variables set up, we need to initiate our application. During the initialization process, set the progress bar (pBar) to invisible. We only want the bar to be visible when we’re uploading an image.
The next function is to open the file browser for the user to select an image.
private function init():void
{
pBar.visible = false;
}
private function selectImageFile(root:File):void
{
var imgFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
root.browseForOpen("Open", [imgFilter]);
root.addEventListener(Event.SELECT, fileSelected);
}
Step 15: Read File Information and Update Input fields
Create a function named “fileSelected” which will fire when the user selects an image. This function will also read that image’s file name and url. Update the “Title” input field with the selected file’s name and target the “Image Preview”, setting it’s URL to the URL of the file selected.
Create two more functions, one to handle the upload of the image to Flickr and the other to track its progress via the progress bar.
Name the first function “uploadFile” with a type of “MouseEvent”. Inside of that function, set the variable that we created earlier, “file” to type “File” and pass in the URL of the image selected by the user. Add two listeners to that variable. The first listener will be a “DataEvent” listening for upload complete and its target function will be called “uploadCompleteHandler”. The second listener will be a progress event and its target will be the function “onProgress”.
Create the second function and name it “onProgress”. Inside of the function set the progress bar to visible and set its source to that of “file”.
private function uploadFile(event:MouseEvent):void
{
file = new File(fileToOpen.url);
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadCompleteHandler);
file.addEventListener(ProgressEvent.PROGRESS, onProgress);
uploader.upload(file, imageTitle.text, imageDesc.text, imageTags.text);
}
private function onProgress(event:ProgressEvent):void
{
pBar.visible = true;
pBar.source = file;
}
Step 17: Upload Complete
Once the upload is complete, Flickr will send a response back to our app letting us know the upload has finished. Flickr’s response back to us will be in the form of XML, we’ll need to parse that XML and determine the response whether it be an “ok” or something else. All we need to know is if the response is “ok” then launch an Alert window stating that the upload succeeded or if the response if anything else, it means that the upload failed and we need to let the user know.
private function uploadCompleteHandler(event:DataEvent):void
{
pBar.visible = false;
trace("upload done");
var xData:XML = new XML(event.data);
trace(xData);
if(xData[0].attribute("stat") == "ok"){
Alert.show("Upload Successful", "Upload Status");
}else {
Alert.show("Upload Failed", "Upload Status");
}
}
Step 18: Call Functions and Initiate Application
At this point, if you test your application nothing will happen. That’s because we haven’t added click functions to our buttons and more importantly, we haven’t initiated our application.
Inside of your main application’s code, scroll down and find the code for the buttons we created using the GUI at the beginning of this tutorial. We’ll need to add “Click” handlers to each button to tell them which function to execute when they are clicked.
The select button will call selectImageFile(fileToOpen) with the variable fileToOpen passed into it.
Now all we need to do is initiate our application. We do this by adding some code to the top of our file under the “WindowedApplication” element. All we need to do is add call the function init() with this applicationComplete. It should look like this:
Once you’ve finished coding your application, it’s time to test it to make sure it works.
Click “debug” in Flex Builder to deploy the application.
The application will alert you to only click “OK” after you log in to Flickr and give permission to the app to access your Flickr account.
Step 20: Select An Image To Upload
After clicking “OK” you’ll see your blank application waiting for input.
Click “Select” and navigate to an image on your local computer. Once selected, click “Open”. You should now see a preview of the image you selected. Go ahead and give it a title and a description. Think of some tags that go along with the image and enter them into the “tags” field, separated by commas. Click “Upload”.
If you were successful you should see the following screen.
Just to make sure the image uploaded successfully, head on over to your Flickr account and view the image you just uploaded.
Step 21: Export as AIR
Now that we know our app is working properly, we can export it as an AIR application. To do that, click “File > Export > Release Build”. There aren’t any settings on the first window that we need to change, so click “Next” and head to the next window.
Create a certificate by filling in the “Publisher Name” and “Password” fields. Browse a location to save the certificate and name it. Click “finish” and wait for your AIR app to build.
Conclusion
Your app is finished, it’s working and you’ve exported it out for AIR. What now? Now you can expand upon this application with some more of the API functions or you can deploy as is.
Thank you for taking the time to work through this tutorial, I hope you enjoyed it. And remember… keep learning!
Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more
Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!