1. Code
  2. JavaScript

Create an Image Rotator in Flash Using XML and ActionScript 3.0

Scroll to top
9 min read

In this tutorial you will learn how to make a simple Image Rotator from scratch using Flash, XML and ActionScript 3.0.

Step 1: Brief Overview

This image rotator is created almost entirely out of code alone.

During the first steps we will set up the Fla file properties and embed some fonts to make the image information look better. We also add a preloader to indicate the automatic transition of the images.

Step 2: Set Up

Open Flash and create a new Flash File (ActionScript 3.0).

Set the stage size to 600 x 300 px and the frame speed to 24fps.

Step 3: Embed Fonts

In order to give a better look to our application we will make use of embedded fonts.

Open the Library Panel (Cmd+L) and right-click in the items area to bring up a context menu.

Select New Font and choose a font you like. Remember to select the actual size you are going to use in the movie.

I used Helvetica Bold for the image title, and FFF Harmony for the description.

Step 4: Preloader

A preloader MovieClip will be used as an indication of progress, this will tell the user that the images are playing automatically.

In this example, I used the Apple Inspired Preloader we created before here on ActiveTuts+. We'll just use the animation, so there's no need to copy the code. Our code will move on to the next image each time the preloader animation loops.

Step 5: Get Some Images

It wouldn't be an Image Rotator without images, so 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.

Images have been resized to 600x300 px to fit the movie size.

Step 6: Write the XML

An XML file will be loaded by the application; this file will contain all information about the images such as Title, URL of the image, and Description.

Open your favorite editor and write:

1
<?xml version="1.0"?>
2
<images>
3
	<image title="Grass 01" src="images/Grass.png" description="Photo by: 100kr on Flickr"/>
4
	<image title="Deep Impact on Planet Color" src="images/Water.png" description="Photo by: spettacolopuro on Flickr"/>
5
	<image title="Yosemite: Fall Colours" src="images/Yosemite.png" description="Photo by: tibchris on Flickr"/>
6
</images>

Step 7: Create the Document Class

Create a new ActionScript Document and save it as ImageRotator.as.

Step 8: Import Necessary Classes

This are the required classes. For a more detailed description about every class, please refer to the Flash Help (Press F1 within Flash).

1
2
package 
3
{
4
5
	import fl.transitions.Tween;
6
	import fl.transitions.easing.Strong;
7
	import fl.transitions.TweenEvent;
8
	
9
	import flash.display.Sprite;
10
	import flash.net.URLLoader;
11
	import flash.net.URLRequest;
12
	import flash.display.Loader;
13
	import flash.text.TextField;
14
	import flash.text.TextFormat;
15
	import flash.text.TextFieldAutoSize;
16
	import flash.text.AntiAliasType;
17
	import flash.utils.Timer;
18
	import flash.events.TimerEvent;
19
	import flash.events.Event;
20
	import flash.events.MouseEvent;

Step 9: Start the Class

The extends keyword defines a class that is a subclass of another class. The subclass inherits all the methods, properties and functions, that way we can use them in our class.

We'll make our document class extend Sprite, as it doesn't need a timeline.

1
2
public class ImageRotator extends Sprite
3
{

Step 10: Declare Variables

These are the variables we will use; each is explained in the comments.

1
2
private var xml:XML; // Stores the xml file info

3
private var urlLoader:URLLoader; //Loads the url of the xml file

4
private var imagesVector:Vector.<Loader> = new Vector.<Loader>(); //Stores the images loaded in the Loader object

5
private var imagesCounter:int = 0;
6
private var tween:Tween;
7
private var lastTarget:*; //Gets the last clicked image, in manual transition mode

8
private var tweening = false;
9
private var infoCounter:int = 0; //Changes the xml info to display

10
private var infoPanel:Sprite = new Sprite();
11
private var titleField:TextField = new TextField();
12
private var description:TextField = new TextField();
13
private var titleFormat:TextFormat = new TextFormat();
14
private var descriptionTF:TextFormat = new TextFormat();
15
private var timer:Timer;
16
private var preloader:Preloader = new Preloader(); //The Preloader in the Library

17
private var added:Boolean; //Checks if the preloader is in stage

18
19
private var titleFont:Helvetica = new Helvetica(); //Instantiate Embedded fonts

20
private var bitmapFont:Harmony = new Harmony();

Step 11: Write Constructor Function

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. In this case, it will be the first code run when our SWF starts.

The initial parameters have default values; this will let us use the class as a document class and as an instance.

The parameters are the URL of the XML file and the time that the Timer object will wait to make a transition between images; this number has to be higher than the duration of the Tween transition (one second by default).

1
2
public function ImageRotator(xmlPath:String = "images.xml", interval:int = 2000):void
3
{

Step 12: Write the Constructor Code

This code goes inside the constructor. It starts the Timer, sets the default text format for the text fields and calls the loadXML function.

1
2
timer = new Timer(interval);
3
4
titleFormat.bold = true;
5
titleFormat.font = titleFont.fontName;
6
titleFormat.color = 0xFFFFFF;
7
titleFormat.size = 14;
8
9
descriptionTF.font = bitmapFont.fontName;
10
descriptionTF.color = 0xEEEEEE;
11
descriptionTF.size = 8;
12
13
titleField.defaultTextFormat = titleFormat;
14
titleField.autoSize = TextFieldAutoSize.LEFT;
15
titleField.embedFonts = true;
16
titleField.antiAliasType = AntiAliasType.ADVANCED;
17
18
description.defaultTextFormat = descriptionTF;
19
description.autoSize = TextFieldAutoSize.LEFT;
20
description.embedFonts = true;
21
22
loadXML(xmlPath);
23
}

Step 13: Load the XML File

This function uses the URLLoader object to load the XML file specified in the constructor's parameter. The parseXML function (in the next step) is set to execute when the load is complete.

1
2
private function loadXML(file:String):void
3
{
4
	urlLoader = new URLLoader(new URLRequest(file));
5
	urlLoader.addEventListener(Event.COMPLETE, parseXML);
6
}

Step 14: Parse the XML File

The xml data is assigned to the xml object, and a function to load the images is called.

1
2
private function parseXML(e:Event):void
3
{
4
	xml = new XML(e.target.data);
5
	loadImages();
6
}

Step 15: Load the Images

A for statement is used to get the number of images in the xml, load the images using a Loader object and store this Loader in a Vector object, which was defined earlier. When the load of an image is complete, the sortImages function is executed.

1
2
private function loadImages():void
3
{
4
	for (var i:int = 0; i < xml.children().length(); i++)
5
	{
6
		var loader:Loader = new Loader();
7
8
		loader.load(new URLRequest(xml.children()[i].@src));
9
10
		imagesVector.push(loader);
11
12
		loader.contentLoaderInfo.addEventListener(Event.COMPLETE, sortImages);
13
14
	}
15
}

Step 16: Sort the images

This function adds the images to the stage and sorts them; when all images are loaded, it calls the functions that create the information panel and the mouse listeners.

1
2
private function sortImages(e:Event):void
3
{
4
	imagesCounter++;
5
6
	for (var i:int = imagesVector.length - 1; i >= 0; i--) //go backwards...

7
	{
8
		addChild(imagesVector[i]); //...so that images at the start of the XML end up at the front

9
	}
10
11
	if (imagesCounter == imagesVector.length) //If all images are loaded

12
	{
13
		createInfoPanel();
14
		timer.addEventListener(TimerEvent.TIMER, autoChange);
15
		timer.start();
16
		addPreloader();
17
		addActions();
18
	}
19
}

Step 17: Add Mouse Listeners to Images

We use a for statement to set the mouse listeners to every image. This is a very simple form of control; when the user clicks an image, the changeImage handler function will be called.

1
2
private function addActions():void
3
{
4
	for (var i:int = 0; i < imagesVector.length; i++)//Gets the number of images

5
	{
6
		//Sets the listener, changeImage function will be executed when an image is clicked

7
		imagesVector[i].addEventListener(MouseEvent.MOUSE_UP, changeImage);
8
	}
9
}

Step 18: Manual Transition

This code will be run when the user clicks an image. Read the comments in the code for details.

1
2
private function changeImage(e:MouseEvent):void
3
{
4
	timer.stop(); //Stop the timer

5
			
6
	if(added) //Check if the preloader is in stage, if true, removes it, if already removed, nothing happens

7
	{
8
		removeChild(preloader);
9
		added = false;
10
	}
11
12
	if (! tweening) //If a transition is not in progress

13
	{
14
		lastTarget = e.target; //Get the clicked image

15
		tween = new Tween(e.target,"alpha",Strong.easeOut,1,0,1,true); //Start a transition

16
		tween.addEventListener(TweenEvent.MOTION_FINISH, changeDepth); //The image will change its depth when the transition is done

17
		tweening = true; //Indicates a transition is in progress

18
19
		infoCounter++; //Changes the child that will be loaded from the xml

20
21
		if (infoCounter >= xml.children().length()) //If the infoCounter is grater than the total number of images

22
		{
23
			infoCounter = 0; //Reset

24
			titleField.text = xml.children()[infoCounter]. @ title; //Apply changes to text fields

25
			description.text = xml.children()[infoCounter]. @ description;
26
		}
27
		else
28
		{
29
			titleField.text = xml.children()[infoCounter]. @ title; //Apply changes to text fields

30
			description.text = xml.children()[infoCounter]. @ description;
31
		}
32
	}
33
}

Step 19: Move Image to Back

The transition between images is based on alpha tween, so you will see the next image when the transition has finished. However, if you click it, you will be clicking the same image as before, although it's not visible. This will fix that.

1
2
private function changeDepth(e:TweenEvent):void //When the alpha is 0

3
{
4
	setChildIndex(lastTarget, 0); //move the image so it is behind the others

5
	lastTarget.alpha = 1; //Restore its visibility

6
	tweening = false; //Mark the tween as being complete

7
}

Step 20: Create Information Panel

This will create a semi-transparent panel, with text generated from the XML's Title and Description tags.

1
2
private function createInfoPanel():void
3
{
4
	//Draw a black rectangle with 50% alpha

5
	infoPanel.graphics.beginFill(0x000000, 0.5);
6
	infoPanel.graphics.drawRect(0, 0, 600, 50);
7
	infoPanel.graphics.endFill();
8
9
	//Position and set the value of the title field

10
	titleField.text = xml.children()[infoCounter]. @ title;
11
	titleField.x = 5;
12
	titleField.y = 5;
13
14
	//Position and set the value of the description field

15
	description.text = xml.children()[infoCounter]. @ description;
16
	description.x = 7;
17
	description.y = 22;
18
19
	infoPanel.y = 250; //Position this panel in the bottom

20
	
21
	//Add the children

22
	infoPanel.addChild(titleField);
23
	infoPanel.addChild(description);
24
25
	addChild(infoPanel);
26
}

Step 21: Handle Automatic Transition

This code handles the automatic transition; it is triggered by the Timer object's TIMER event.

1
2
private function autoChange(e:TimerEvent):void
3
{
4
	infoCounter++; //Changes the child that will be loaded from the xml

5
6
	lastTarget = imagesVector[xml 1="-" 2="infoCounter" language=".children().length()"][/xml]; //Gets the last image that was tweened
7
	tween = new Tween(imagesVector[xml 1="-" 2="infoCounter" language=".children().length()"][/xml],"alpha",Strong.easeOut,1,0,1,true); //Creates an alpha tween
8
9
	/* The same actions of the manual transition, change info etc. */
10
11
	tween.addEventListener(TweenEvent.MOTION_FINISH, changeDepth);
12
	tweening = true;
13
14
	if (infoCounter >= xml.children().length())
15
	{
16
		infoCounter = 0;
17
		titleField.text = xml.children()[infoCounter]. @ title;
18
		description.text = xml.children()[infoCounter]. @ description;
19
	}
20
	else
21
	{
22
		titleField.text = xml.children()[infoCounter]. @ title;
23
		description.text = xml.children()[infoCounter]. @ description;
24
	}
25
}

Step 22: Position the Preloader MovieClip

This chunk of script adds and places the preloader.

1
2
private function addPreloader():void
3
{
4
	added = true;
5
			
6
	preloader.scaleX = 0.08;
7
	preloader.scaleY = 0.08;
8
		
9
	preloader.x = (600 - preloader.width/2) - 12;
10
	preloader.y = (300 - preloader.height/2) - 12;
11
		
12
	addChild(preloader);
13
}
14
}
15
}

This completes the ImageRotator class.

Step 23: Using the Class

There are two ways to use this class. You can use it in your code as an instance or as the document class with the default parameters we set earlier.

If you choose to instantiate this class and use it in your code, this is an example of how to use it:

1
2
import ImageRotator;
3
4
var ir:ImageRotator = new ImageRotator("images.xml", 1100);
5
6
addChild(ir);

This way you can set the xml file to be loaded and the interval of the transition without the need to edit the class code.

Otherwise, see the next step.

Step 24: Using the Document Class

In the .fla file, go to the Properties Panel and write ImageRotator in the Class field. Remember that this will use the default parameters.

Conclusion

This is just an example of an image rotator, and a good way to start making your own awesome image gallery.

Thanks for reading!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.