Archive for the ‘Flash’ Category

Deconstruct red-issue.com

Sunday, March 22nd, 2009

In one of my Flash courses taught at Humber College we often choose web sites to deconstruct. Today we have chosen red-issue.com.

First let’s figure out what we want to learn from this web site. We are going to create a grid of images where each image will occupy the full screen. This grid will be navigated by drawing arrows.

First lets import all the Flash and custom classes we will need:

import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.events.Event;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
import com.foxaweb.ui.gesture.*;

The last import statement is a class that helps us recognize mouse gestures. The Mouse Gestures Class was written by Didier Brun.

Next we need a few variables to define the grid dimensions and to keep track of what row and column we are currently looking at.

var verticalCounter:Number = new Number();
var horizontalCounter:Number = new Number();
var gridWidth:Number=new Number(4);
var gridHeight:Number=new Number(3);

On the Enter Frame Event we will check the values in the horizontalCounter and verticalCounter variable and position the grid accordingly. That way when someone draws a down arrow we will simply add one to the verticalCounter variable.

stage.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
function enterFrameHandler(evt:Event):void {
     var targetX:Number = new Number(stage.stageWidth * horizontalCounter);
     grid_mc.x += (targetX - grid_mc.x) / 3;
     var targetY:Number = new Number(stage.stageHeight * verticalCounter);
     grid_mc.y += (targetY - grid_mc.y) / 3;
}

Wen using the Mouse Gestures Class we need to tell the Class what gestures to look for. These gestures are determined by a set of numbers. For example a up arrow starting from the left consists of a 7 motion and then a 1 motion. Here are the motions tracked and the numbers for each.

Here is the code to create a new Mouse Gesture and add the four different directions as well as the zoom in and zoom out gestures.

var mg:MouseGesture = new MouseGesture(stage);
mg.addGesture("UP","71");
mg.addGesture("UP","53");
mg.addGesture("DOWN","17");
mg.addGesture("DOWN","35");
mg.addGesture("LEFT","13");
mg.addGesture("LEFT","75");
mg.addGesture("RIGHT","31");
mg.addGesture("RIGHT","57");
mg.addGesture("OUT","0");
mg.addGesture("OUT","4");
mg.addGesture("IN","4321076542");

Now with this class we are going to listen for a few specific events.

mg.addEventListener(GestureEvent.GESTURE_MATCH,matchHandler);
mg.addEventListener(GestureEvent.NO_MATCH,noMatchHandler);
mg.addEventListener(GestureEvent.START_CAPTURE,startHandler);
mg.addEventListener(GestureEvent.STOP_CAPTURE,stopHandler);

A Mouse Gesture is defined by the user pressing their mouse down, moving the mouse and then releasing. When a Mouse Gesture matches one of the items defines in our list the matchHandler function is executed. This function makes the necessary changes to verticalCounter or horizontalCounter and then removes the drawing.

function matchHandler(evt:GestureEvent):void{
     switch (evt.datas){
          case "UP":
               if(verticalCounter < 0){
                    verticalCounter++;
               }
          break;
          case "DOWN":
               if(verticalCounter > 1 - gridHeight){
                    verticalCounter--;
               }
          break;
          case "LEFT":
               if(horizontalCounter > 1 - gridWidth){
                    horizontalCounter--;
          }
          break;
          case "RIGHT":
               if(horizontalCounter < 0){
                    horizontalCounter++;
               }
          break;
          case "IN":
               // Zoom in code would go here
          break;
          case "OUT":
               // Zoom out code would go here
          break;
     }
     var tweenOut:Tween = new Tween(draw_mc,"alpha",Strong.easeOut,1,0,6);
}

This code was taken from the GesturesDemo.as file that comes with the Mouse Gestures Class. When the Start Capture Event is triggered this code draws whatever the user does.

function startHandler(e:GestureEvent):void{
     draw_mc.graphics.clear();
     draw_mc.alpha = 1;
     draw_mc.graphics.lineStyle(4,0x444444);
     draw_mc.graphics.moveTo(mouseX,mouseY);
     addEventListener(Event.ENTER_FRAME,capturingHandler);
}

When the user lets go of their mouse the Stop Capture Event is triggered and executes the startHandler function. This function stops the drawing initialized by the startHandler function.

function stopHandler(e:GestureEvent):void{
     removeEventListener(Event.ENTER_FRAME,capturingHandler);
}

This function actually performs the drawing. It is started by the startHandler function and is stopped by the stopHandler function.

function capturingHandler(e:Event):void{
     draw_mc.graphics.lineTo(mouseX,mouseY);
}

When the user releases the mouse button if there is no match the noMatchHandler function removes the drawing.

function noMatchHandler(e:GestureEvent):void{
     var tweenOut:Tween = new Tween(draw_mc,"alpha",Strong.easeOut,1,0,6);
}

The next set of code creates the photo grid and makes any necessary changes when the Stage is re-sized. You can get a much more in depth description of this code from the Photo Grid post.

stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;

This list of images could eventually come from an XML document but for now we will just use an array.

var imageDir:String = new String( "http://adambenjamin.com/blog/wp-content/" );
var gridArray:Array=new Array(
     ({image:"img_0001.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0002.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0003.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0004.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0005.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0006.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0007.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0008.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0009.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0010.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0011.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0012.jpg",imageWidth:800,imageHeight:532}));

var movieArray:Array = new Array();
var maskArray:Array = new Array();
var loaderArray:Array = new Array();

stage.addEventListener(Event.RESIZE, resizeHandler);
function resizeHandler(evt:Event):void {
     for (var i:int = 0; i < gridArray.length; i ++) {
          resizeMask(i);
          resizeImage(i);
          reposition(i);
     }
}

for (var i:int = 0; i < gridArray.length; i ++) {
     maskArray[i] = new MovieClip();
     maskArray[i].graphics.lineStyle(0,0x000088);
     maskArray[i].graphics.beginFill(0x000088);
     maskArray[i].graphics.drawRect(0,0,1,1);
     maskArray[i].graphics.endFill();
     resizeMask(i);
     grid_mc.addChild(maskArray[i]);
     movieArray[i] = new MovieClip();
     var request:URLRequest=new URLRequest(imageDir + gridArray[i]["image"]);
     loaderArray[i] = new Loader();

     loaderArray[i].load(request);
     resizeImage(i);
     movieArray[i].addChild(loaderArray[i]);
     grid_mc.addChild(movieArray[i]);
     movieArray[i].mask=maskArray[i];
     reposition(i);
}

function reposition(i:int):void{
     maskArray[i].x = i % gridWidth * Number(stage.stageWidth);
     maskArray[i].y = Math.floor( i / gridWidth ) * Number(stage.stageHeight);
     movieArray[i].x = i % gridWidth * Number(stage.stageWidth);
     movieArray[i].y = Math.floor( i / gridWidth ) * Number(stage.stageHeight);
}

function resizeMask(i:int):void{
     maskArray[i].width = Number(stage.stageWidth);
     maskArray[i].height = Number(stage.stageHeight);
}

function resizeImage(i:int):void {
     var widthRatio:Number = Number(stage.stageWidth)/gridArray[i]["imageWidth"];
     var heightRatio:Number = Number(stage.stageHeight)/gridArray[i]["imageHeight"];
     if( widthRatio > heightRatio){
          movieArray[i].scaleX = widthRatio;
          movieArray[i].scaleY = widthRatio;
     }else{
          movieArray[i].scaleX = heightRatio;
          movieArray[i].scaleY = heightRatio;
     }
}

The Flash plugin is required to view this object.

Download Red Issue FLA

Flash XML Gallery

Friday, February 27th, 2009

This post will walk through the construction of a simple XML and Flash gallery. If you want to use the images and XML file we are referring to in this example you can download our XML document here and download our images here. Our gallery will simply load the first image and then with each click it’ll load the next image form our XML document.

The Flash plugin is required to view this object.

First of all here is the XML we will be working with:

<?xml version="1.0" encoding="utf-8"?>
<gallery>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0001.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Field at Night</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0002.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Van on the Road</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0003.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Van on the Road Close Up</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0004.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Mountains</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0005.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Edge of a Cliff</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0006.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Another Road</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0007.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Tight Path</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0008.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Yellow Pickup</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0009.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Power Lines</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0010.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Pig</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0011.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Drying Coffee Beans</title>
     </photo>
     <photo>
          <filename>http://adambenjamin.com/blog/wp-content/img_0012.jpg</filename>
          <width>800</width>
          <height>531</height>
          <title>Homes</title>
     </photo>
</gallery>

In this example the only piece of information we will need is the filename. In future posts we may use the image titles and dimensions.

First we need to import a few Classes:

import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;

Next we need a Movie Clip to load images into and apply Tweens to:

var containerMovie:MovieClip = new MovieClip();
addChild(containerMovie);

Then we define a URL Loarder and an XML Object:

var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();

We are going to need two variables: one to keep track of what image we are currently viewing and another to keep track of whether or not we are in the progress of loading the next image.

var galleryCounter:Number=new Number(0);
var galleryStatus:Boolean=new Boolean(false);

Then we are gong to add an Event LIstener to the main Movie Clip to listen for Click Events.

containerMovie.buttonMode = true;
containerMovie.addEventListener(MouseEvent.CLICK,clickHandler);

When some one clicks the main Movie Clip we check to make sure another image isn’t half way through loading; and if it isn’t we add one to the counter Variable, check to make sure it hasn’t gone too high and then load that photo.

function clickHandler(evt:MouseEvent):void {
     if (galleryStatus==false) {
          galleryCounter++;
          if (galleryCounter>=xmlData.photo.length()) {
               galleryCounter=0;
          }
          loadPhotoStep1(galleryCounter);
     }
}

Now that our containers and butons are all set up lets load our XML.

xmlLoader.load(new URLRequest("gallery.xml"));

Once that loading is complete we put the loaded information into our XML Object and start eh first step of loading our image.

xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
function LoadXML(e:Event):void {
     xmlData=new XML(e.target.data);
     loadPhotoStep1(galleryCounter);
}

Setp 1 - we save the loaded image number into our galleryCounter variable and set galleryStatus to true. This prevents our clickHandler function above from loading another image before this one has finished loading. And we Tween the Alpha out of the current image.

function loadPhotoStep1(photoNumber:Number):void {
     galleryCounter=photoNumber;
     galleryStatus=true;
     var tweenOut:Tween=new Tween(containerMovie,"alpha",Strong.easeOut,1,0,15);
     tweenOut.addEventListener(TweenEvent.MOTION_FINISH,loadPhotoStep2);
}

Step 2 - once the first Tween has completed we load empty the container Movie Clip and load in the new image.

function loadPhotoStep2(evt:TweenEvent):void {
     var imageLoader:Loader = new Loader();
     var imageRequest:URLRequest=new URLRequest(xmlData.photo[galleryCounter].filename);
     imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadPhotoStep3);
     imageLoader.load(imageRequest);
     emptyContainer();
     containerMovie.addChild(imageLoader);
}

One the image has loaded in we Tween the Alpha back in.

function loadPhotoStep3(evt:Event):void {
     var tweenIn:Tween=new Tween(containerMovie,"alpha",Strong.easeOut,0,1,15);
     tweenIn.addEventListener(TweenEvent.MOTION_FINISH,loadPhotoStep4);
}

Once that Tween is complete we set galleryStatus back to false so the next time the user clicks the Movie Clip i’s good to go!

function loadPhotoStep4(evt:Event):void {
     galleryStatus=false;
}

This last function removes all Children from the containerMovie Movie Clip. It is called by the step 2 function.

function emptyContainer() :void {
     for (var i:int; i < containerMovie.numChildren; i++){
          containerMovie.removeChildAt(i);
     }
}

Download the Gallery Flash File

Download a Version of this Gallery with Thumbnails

My Own Number

Friday, February 27th, 2009

When teaching Flash one of the questions that often comes up is how to generate a menu based on XML. By the time the question gets to me usually the FLA is to the point where he XML is loaded, there is an imported Object from the library for each item in the XML and those Objects are clickable. Where it gets difficult is having each of those items remember what XML item they belong to.

In Actionscript 2.0 this was easy. We could assign whatever properties/variables/functions to whatever and everything would work out fine. Using Actionscript 3.0 we now hove to do this properly….well kind of.

First we need some XML to import. Lets use this very generic XML file.

<?xml version="1.0" encoding="utf-8"?>
<root_element>
     <item>
          <number>1</number>
          <title>Title Number 1</title>
          <image>image1.jpg</image>
     </item>
     <item>
          <number>2</number>
          <title>Title Number 2</title>
          <image>image2.jpg</image>
     </item>
     <item>
          <number>3</number>
          <title>Title Number 3</title>
          <image>image3.jpg</image>
     </item>
     <item>
          <number>4</number>
          <title>Title Number 4</title>
          <image>image4.jpg</image>
     </item>
</root_element>

Download the Example XML Document

Now lets go through two different methods of achieving this.

Method One: Avoiding External AS Files

The proper way to do this would be to create a Custom Class using an external Actionscript file and maybe partner this with a Library Object with the same name. However, this can be achieved without an External Actionscript file…it’s a little dirty but it’ll work.

Open up a new Actionscript 3.0 file and create a new Symbol with the following properties:

In this new Object give it the following timeline:

On the number text box put a Dynamic Text Field with the Instance name number_tb. On the Title layer put a Dynamic Text Field with the instance name title_tb. And on the background layer put some sort of background. IT should look something like this:

Now go back to the Stage and select Frame 1. The first thing we need to do is create a URL Request, a URL Loader and an XML Object:

var exampleXML:XML = new XML();
var exampleRequest:URLRequest=new URLRequest(&quot;flash_number_example.xml&quot;);
var exampleLoader:URLLoader = new URLLoader();

Next we need to load the URL Request using the URL Loader.

exampleLoader.load(exampleRequest);

When the loading is complete we will trigger the completeHandler Function.

exampleLoader.addEventListener(Event.COMPLETE,completeHandler);

And lastly we need to define that function.The first line takes the loaded data from our URL Loader and puts it into an XML object. Before we moved it into an XML Object the data would have been treated as text. This allows us to do all sorts of XML type things with it.

Next we loop through each item in the XML Object and create a copy of an ItemObject. For each ItemObject we set the test in the title_tb Text Field to the title from the XML and the number_tb Text Field to the item number. Next we position the Item Object, give it it’s Button actions and lastly add it to the Stage.

Special thanks to Mazoonist for the mouseChildren line of code. This solution was found in an actionscript.og forum post. This line makes sure the whole button is clickable. If we did not have this line the button would be clickable but you would not get the point mouse whenever your mouse is over a text box.

function completeHandler(evt:Event):void {
     exampleXML=XML(evt.target.data);
     for (var i:int=0; i<exampleXM.item.length(); i++ )
          var nextItem:ItemObject = new ItemObject();
          nextItem.title_tb.text = String(exampleXML.item[i].title);
          nextItem.number_tb.text = String(i);
          nextItem.x = 141 * i;
          nextItem.addEventListener(MouseEvent.CLICK,clickHandler);
          nextItem.mouseChildren = false;
          nextItem.buttonMode = true;
          addChild(nextItem);
     }
}

And of course we need a function to execute on he click of our Buttons. At this point this code just traces it’s own number. Now that each item know it’s number it can go back to the XML object and retrieve anything else it may need.

function clickHandler(evt:Event):void {
     trace(evt.target.number_tb.text);
}

Download the Hack Version FLA

Method Two: External AS Files

In this method we will use a Library Object in Partnership with an external AS file. Start by opening a new Actionscript 3.0 document. Just like the above example insert a new symbol with the following properties:

In that new symbol give it the following timeline:

On the title layer put a Text Field with the Instance name title_tb and on the background layer put some sort of background.

Next we need an external AS file to help define our ItemObject Object. Creating a Custom Class Actionscript file is exactly like creating an object in real life. We give the Object a name and we define what properties the Object has. In our case we are creating an ItemObject. From looking at our last method we know that an ItemObject is a type of MovieClip; which is actually a little over kill. We can go one step back. So our ItemObject is a type of Sprite.

The different between a Sprite and a MovieClip is that a MovieClip is a Sprite with a timeline. So MovieClip have properties like currentframe and all sorts of timeline related stuff.

When creating a Custom Class we use the package syntax and first list all pre-existing Classes the this Custom Class requires. So in our example we need the Sprite and MouseEvent Classes.

package {
     mport flash.display.Sprite;
     import flash.events.MouseEvent;

Next we start our Class and provide the base Class; in this case a Sprite:

     public class ItemObject extends Sprite {

We now need ot list what properties this new Custom Class has. In our example above the ItemObject has two properties that a Spite doesn’t have. We need a place to store the text and a pace to store the number.

          var itemText:String;
          var itemNumber:Number;

Next we need what is called a Constructor. A Constructor is the code that is executed when the Class is created. In the constructor definition we also specify what values are required to initially create an instance of our Custom Class.

In our example we need the text and the number to create an instance of an ItemObject. This function then saves the two provided values in the two properties defined above, adds a Rollover action and sets a few default properties.

          public function ItemObject(itemText:String,itemNumber:Number){
               this.itemText = itemText;
               this.itemNumber = itemNumber;
               this.title_tb.text = this.itemText;
               this.addEventListener(MouseEvent.CLICK,clickHandler);
               this.mouseChildren = false;
               this.buttonMode = true;
          }

Finally we need the clickHandler function called above. In this case we just trace the ItemObject’s number. And close the parenthesis from the open Class and Package lines above.

          public function clickHandler(evt:MouseEvent):void {
               trace(this.itemNumber);
          }

Download the Proper Version FLA

Flash Photo Grid

Sunday, February 22nd, 2009

In this post we are going to create a grid of images that is resizable using two text boxes. This task came from the Deconstruct red-issue.com post.

We are going to build a Flash file that will take the list of images and put the in a grid using the gridWidth and gridHeight as well as the text from the width_tb and height_tb text Fields.

To make reusing this file easier we are first going to define a variable to determine the directory the images are stored in. If you want to use the same images as this example you can download them here. Lets assume the images are in an images directory in the same folder as our SWF file.

var imageDir:String = new String( "images /" );

Once this file was being used in a web site, like red-issue.com, it would like get it’s list of images from an XML file. For now lets just store them in an Array.

var gridArray:Array=new Array(
     ({image:"img_0001.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0002.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0003.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0004.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0005.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0006.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0007.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0008.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0009.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0010.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0011.jpg",imageWidth:800,imageHeight:532}),
     ({image:"img_0012.jpg",imageWidth:800,imageHeight:532}));

Next we need a vaiable to determine the width and height of the photo grid.

var gridWidth:Number=new Number(4);
var gridHeight:Number=new Number(3);

Each photo im our grid is going to need a Movie Clip, a Mask and a Loader. Lets assume the number of photos we are putting in our grid is unknown. This means we will need to store these items in three sepereate Arrays.

var movieArray:Array = new Array();
var maskArray:Array = new Array();
var loaderArray:Array = new Array();

In this example we are determining the width of each photo using two Text Fields. When we go back to the Deconstruct red-issue.com post we will be using the Stage width and height. This next excerpt of code will only be used for this example.

width_tb.tabIndex = 1;
height_tb.tabIndex = 2;
submit_btn.tabIndex = 3;
width_lb.text = "Width:";
width_tb.text = "100";
height_lb.text = "Height:";
height_tb.text = "100";
submit_btn.label = "Resize";

When the Stage is resized, or in this example when the submit Button is pressed, we need to re-size our images and masks and then re-position everything in our grid. Lets break this into three seperate steps. All our clickHandler function has to do is trigger these three functions. These three functions will assume that the Movie Clips, Masks and Loaders already exist.

submit_btn.addEventListener(MouseEvent.CLICK,clickHandler);
function clickHandler(evt:Event):void {
     for (var i:int = 0; i < gridArray.length; i ++) {
          resizeMask(i);
          resizeImage(i);
          reposition(i);
     }
}

The first functionwill reposition the Movie Clips and Masks based on the new image width and height.

function reposition(i:int):void{
     maskArray[i].x = i % gridWidth * Number(width_tb.text);
     maskArray[i].y = Math.floor( i / gridWidth ) * Number(height_tb.text);
     movieArray[i].x = i % gridWidth * Number(width_tb.text);
     movieArray[i].y = Math.floor( i / gridWidth ) * Number(height_tb.text);
}

The second function will resize the Masks.

function resizeMask(i:int):void{
     maskArray[i].width = Number(width_tb.text);
     maskArray[i].height = Number(height_tb.text);
}

And the last function will resize the Movie Clips. This is a little more complicated then resizing the masks as the Movie Clips need to remain proportianate.

function resizeImage(i:int):void {
     var widthRatio:Number = Number(width_tb.text)/gridArray[i]["imageWidth"];
     var heightRatio:Number = Number(height_tb.text)/gridArray[i]["imageHeight"];
     if( widthRatio > heightRatio){
          movieArray[i].scaleX = widthRatio;
          movieArray[i].scaleY = widthRatio;
     }else{
          movieArray[i].scaleX = heightRatio;
          movieArray[i].scaleY = heightRatio;
     }
}

Now that all of our functions are set to go we just need to crreate our Masks, Loaders and Movie Clips. The first seven lines of our this for loop create and resize our Masks, the next seven after that create the image Movie Clips and load our images in and finally the two lines set the Masks and execite the reposition function.

for (var i:int = 0; i < gridArray.length; i ++) {
     maskArray[i] = new MovieClip();
     maskArray[i].graphics.lineStyle(0,0x000088);
     maskArray[i].graphics.beginFill(0x000088);
     maskArray[i].graphics.drawRect(0,0,1,1);
     maskArray[i].graphics.endFill();
     resizeMask(i);
     grid_mc.addChild(maskArray[i]);
     movieArray[i] = new MovieClip();
     var request:URLRequest=new URLRequest(imageDir + gridArray[i]["image"]);
     loaderArray[i] = new Loader();
     loaderArray[i].load(request);
     resizeImage(i);
     movieArray[i].addChild(loaderArray[i]);
     grid_mc.addChild(movieArray[i]);
     movieArray[i].mask=maskArray[i];
     reposition(i);
}

The Flash plugin is required to view this object.

Download the Image Grid Flash File

Flash XML Weather Feed

Sunday, February 22nd, 2009

Integrating Flash with XML is increasingly becoming more and more common and useful! Working with XML has also become a whole lot easier with Actionscript 3.0. In this example we will create a Flash file that will display the current weather. We will get our weather information from Boy Genius. The weather feeds are available here. For this example we are going to use the weather from Toronto Ontario Canada.

Here is the XML we will be working with:

<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/xsl" href="/weather.xsl" alternate="no" ?>
<city>
     <name>Toronto</name>
     <state>Ontario</state>
     <temperatures>
          <fahrenheit>27</fahrenheit>
          <celsius>-2</celsius>
     </temperatures>
     <conditions>FLURRIES</conditions>
     <dewpoint>18</dewpoint>
     <relative_humidity>69</relative_humidity>
     <wind>W28G33</wind>
     <wind_english>West 28 MPH Gusts Reaching 33 MPH </wind_english>
     <barometric_pressure>29.88R</barometric_pressure>
     <notes></notes>
     <wind_chill_fahrenheit>11</wind_chill_fahrenheit>
     <heat_index_fahrenheit>Not Applicable</heat_index_fahrenheit>
     <image>http://www.srh.noaa.gov/weather/images/fcicons/na.gif</image>
     <coordinates>
          <latitude>N/A</latitude>
          <longitude>N/A</longitude>
     </coordinates>
     <last_updated>February 22, 2009 18:19:18 GMT</last_updated>
     <last_updated_seconds_gmt>1235344758</last_updated_seconds_gmt>
     <info_courtesy_of>The National Weather Service</info_courtesy_of>
     <source_url>http://weather.noaa.gov/pub/data/raw/as/asus43.kfgf.rwr.fgf.txt</source_url>
     <feed_problems_contact>xml@boygenius.com</feed_problems_contact>
     <xml_generation_script_author>Todd Finney, Boy Genius Incorporated</xml_generation_script_author>
</city>

Writing the Actionscript to import this XML and display it on the stage is a common assignment I give to my students. In this example we are just going to import the city, state and the image.

First lest define a Text Format Object to use with the weather city and state.

var newFormat:TextFormat = new TextFormat();
newFormat.size = 20;
newFormat.color = 0x666666;
newFormat.font = "Arial";

Next we need to define a URL Loader and an XML Object. We will load the XML using the URL Loader and then on the Load Complete Event we will put the content into an XML Object.

When the Loader Complete Event is triggered all the information about that event will go into the variable evt defined in the function definition. Inside that Event variable is the target of the event and in this case the data loaded. We need to put that data, which is just text at this point, and put it in an XML Object. This was Flash can do all sorts of XML type things.

var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("http://weather.boygenius.com/feeds/ontario-toronto.xml"));
function LoadXML(evt:Event):void {
     xmlData=new XML(evt.target.data);
}

Inside the loadXML function we need to add code that will create a Text Field, use our Text Format Object defined earlier and display the city and state from the XML document. Add the following code to the loadXML function.

To get the city and state our of our XML Object we simply refer to the XML Object and then add a dot and the item we are looking for. So in this example we want xmlData.name and xmlData.state. This gets a little more complicated when there are multiple copies of items in an XML document. For example pulling information about one image out of an XML document that includes information about many images.

     var nameTextField:TextField = new TextField();
     nameTextField.text = String( xmlData.name ) + ", " + String( xmlData.state );
     nameTextField.selectable = false;
     nameTextField.width = 200;
     nameTextField.x = 10;
     nameTextField.y = 10;
     nameTextField.setTextFormat( newFormat );
     addChild(nameTextField);

And lastly we need to add more code to the loadXML function to load the weather image and add it to the stage.

     var imageLoader:Loader = new Loader();
     var imageRequest:URLRequest = new URLRequest(xmlData.image);
     imageLoader.load(imageRequest);
     imageLoader.x = 10;
     imageLoader.y = 100;
     addChild(imageLoader);

The current weather in Toronto Ontario Canada is:

The Flash plugin is required to view this object.

Download the Flash Weather XML File

For anyone who has had some experience with Flash and XML you will quickly learn about a cross-domain policy. For some reason Flash has added a security feature to Flash which prevents an SWF from loading content from another domain at run-time. There is lots of information about this on the Adobe web site. In theory this isn’t a bad idea; trying to prevent people from using other people’s content and their bandwidth is kind of noble. Except this security feature is so easy to get around they may as well have not built it in.

Our Weather example above will work fine when previewing the file in Flash. As soon as you put the file online Flash will refuse to load the XML from the Boy Genius site because they do not have a cross-domain policy. All we have to do is create a PHP file to grab the weather XML from Boy Genius and regurgitate it. Here is a three line PHP file that will regurgitate what ever XML file you tell it to.

<?php
header ("content-type: text/xml");
$file = file( $_GET['url'] );
echo implode( $file, chr(13) );
?>

Lets say for example we want to load the Toronto weather from the Boy Genius web site. All we need to do is call the above file, lets say it is called xmlCaller.php, and pass it a URL. The XML call in Flash would be:

xmlCaller.php?url=http://weather.boygenius.com/feeds/ontario-toronto.xml