Advertisement
  1. Code
  2. Coding Fundamentals
  3. XML

Create a Shuffle Gallery in Flash Using XML and ActionScript 3.0

Scroll to top
10 min read

In this tutorial I'll explain how to access and use the Display List whilst creating an XML based image gallery with ActionScript 3.0.

Step 1: Overview

Using XML we'll dynamically load and obtain information about the images, give them a random center position, add a frame, add drag functionality, and lastly, we'll use a tween to handle the zoom animation.

Step 2: Let's Get Started

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

flash shuffle photo gallery

Set the stage size to 600x350 and add a gray radial gradient (#EEEEEE, #DDDDDD).

”flash”flash”flash

Step 3: Adding a Preloader

We're going to add a preloading animation to tell the user when the content is loading. In this case I used the Apple inspired preloader that we created before. Since we're going to use only the animation, there's no need to import the class or use an Export Identifier.

Place the preloader on the stage and center it.

flash shuffle photo galleryflash shuffle photo galleryflash shuffle photo gallery

Step 4: Embedding a Font

We're going to embed a font, a super easy task when adding a TextField to the Stage in the Flash IDE, but a little different using ActionScript.

Open the Library Panel and right-click in the items area without selecting one, a contextual menu will appear.

flash shuffle photo gallery

Click on "New Font" to open a dialog window, give a name to your font and select the one you want to use as shown in the following image.

flash shuffle photo galleryflash shuffle photo galleryflash shuffle photo gallery

This will create a class of the font you selected, we'll instantiate this in Step 9.

Step 5: XML

Let's create the XML file.

Open your prefered XML or Text editor and write:

1
2
<?xml version="1.0" encoding="UTF-8"?>
3
4
<images>
5
	<image src="images/image.jpg" title="This is image 1"/>
6
	<image src="images/image2.jpg" title="This is image 2"/>
7
	<image src="images/image3.jpg" title="This is image 3"/>
8
	<image src="images/image4.jpg" title="This is image 4"/>
9
	<image src="images/image5.jpg" title="This is image 5"/>
10
</images>

When you're done, save it as "images.xml" in your xml folder.

Step 6: ActionScript

The code that we'll use will be written in a single class that will be used as the Document Class in the FLA file.

Create a new ActionScript File (File > New)

flash shuffle photo gallery

Save it as "Main.as".

flash shuffle photo galleryflash shuffle photo galleryflash shuffle photo gallery

Step 7: Package

We'll begin with:

1
2
package classes
3
{

The package keyword allows you to organize your code into groups that can be imported by other scripts, it's recommended to name them starting with a lowercase letter and use intercaps for subsequent words for example: galleryClasses.

If you don't want to group your files in a package or you have only one class, you can use it right from your source folder, but the idea is to be organized.

Step 8: Required Classes

1
2
import flash.display.Sprite;
3
import flash.display.MovieClip;
4
import flash.net.URLLoader;
5
import flash.net.URLRequest;
6
import flash.display.Loader;
7
import flash.events.Event;
8
import flash.filters.BitmapFilter;
9
import flash.filters.DropShadowFilter;
10
import flash.text.TextFormat;
11
import flash.text.TextField;
12
import flash.text.AntiAliasType;
13
import flash.events.MouseEvent;
14
import fl.transitions.Tween;
15
import fl.transitions.easing.Strong;
16
import fl.transitions.TweenEvent;

These are the classes that we'll need to make this gallery. If you need help with a specific class please use the Flash Help (F1).

Step 9: Extending the Class

1
2
public class Main extends MovieClip
3
{

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're going to use MovieClip specific methods and properties so we extend using the MovieClip Class.

Step 10: Variables

1
2
var xml:XML; // The XML Object that will parse the XML File

3
var images:Array = new Array(); //This array will store the images loaded

4
var imagesLoaded:int = 0; //A counter, counts the images loaded

5
var imagesTitle:Array = new Array(); //The title properties of the XML File

6
var tween:Tween; //Handles the animation

7
var zoomed:Boolean = false; //Checks if a picture is zoomed, false by default

8
var canClick:Boolean = true; //Checks if the user can click a picture to zoom it, true by default

9
var lastX:int; //Stores the x property of the last picture that was clicked

10
var lastY:int; //Stores the y property of the last picture that was clicked

11
var textformat:TextFormat = new TextFormat(); //A TextFormat Object

12
var screen:Sprite = new Sprite(); //A black screen to focus on the active picture

13
14
var formatFont:Avenir = new Avenir(); //This is the embedded font

Step 11: Constructor

The constructor is a function that runs when an object is created from a class. This code is the first to execute when you make an instance of an object or when using the Document Class.

In this function we'll set the properties of the TextFormat object that we'll use to display a title or a description of each image. Create the black screen that appears when the user clicks on a picture and call the function which loads the desired XML file.

1
2
public function Main():void
3
{
4
	textformat.color = 0xFFFFFF;
5
	textformat.font = formatFont.fontName;
6
	textformat.size = 17; //Use the same size you used when embedding the font from the Library

7
8
	screen.graphics.beginFill(0x111111, .75);
9
	screen.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
10
	screen.graphics.endFill();
11
12
	loadXML("xml/images.xml");
13
}

Step 12: XML Loader Function

This function loads the XML file provided by the "file" parameter. We also add a listener to handle when the load is complete.

1
2
private function loadXML(file:String):void
3
{
4
	var urlLoader:URLLoader = new URLLoader();
5
	var urlReq:URLRequest = new URLRequest(file);
6
7
	urlLoader.load(urlReq);
8
	urlLoader.addEventListener(Event.COMPLETE, handleXML);
9
}

Step 13: Parse XML

Here we convert the loaded XML file to a valid XML object using the parameter "data" of the URLLoader. Then we use a "for" statement to create a Loader for every image in the XML. Additional information is found in the commentary.

1
2
private function handleXML(e:Event):void
3
{
4
	xml = new XML(e.target.data);
5
6
	for (var i:int = 0; i < xml.children().length(); i++)
7
	{
8
		var loader:Loader = new Loader();
9
10
		loader.load(new URLRequest(String(xml.children()[i].@src)));
11
12
13
		images.push(loader); //Adds the Loaders to the images Array to gain access to them outside this function

14
		imagesTitle.push(xml.children()[i].@title); //Adds the title attribute content to the array to use it outside this function

15
16
		loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded); //A listener to the function that will be executed when an image is loaded

17
	}
18
}

Step 14: Images Loaded

When a Loader has loaded an image from the XML, the following code is executed:

1
2
private function loaded(e:Event):void
3
{
4
	imagesLoaded++; //Adds one to the imagesLoaded variable

5
6
	if (xml.children().length() == imagesLoaded) //When all images are loaded...

7
	{
8
		removeChild(preloader); //Removes the Preloader MovieClip

9
		prepareImages(); //This function is explained in the next step

10
	}
11
}

Step 15: Prepare Images

This function will add the frame, the TextField to display the title or description, the black background used for that and a Shadow Filter. Let's take it in parts.

1
2
private function prepareImages():void
3
{
4
	for (var i:int = 0; i < images.length; i++) //These actions will be applied to all the images loaded so we use a "for" and the "images" array to do that

5
	{
6
		var container:Sprite = new Sprite(); //A container that will store the image, frame, TextField, TextField background and shadow

7
		var frame:Sprite = new Sprite(); //The Frame Sprite

8
		var infoArea:Sprite = new Sprite(); //The TextField background

9
		var infoField:TextField = new TextField(); //The TextField

Step 16: Image Frame

This creates a white frame around the image.

1
2
frame.graphics.beginFill(0xFFFFFF);
3
frame.graphics.drawRect(-20, -20, images[i].width + 40, images[i].height + 80);
4
frame.graphics.endFill();

The rectangle will be positioned under the image to be used as a frame.

Step 17: Information Background

This creates a black rectangle in the bottom part of the image, where the TextField will be.

1
2
infoArea.graphics.beginFill(0x111111, 0.75);
3
infoArea.graphics.drawRect(0, 0, images[i].width, 60);
4
infoArea.graphics.endFill();
5
infoArea.y = images[i].height - 60;

Step 18: Image Information

The following code sets the TextField properties and adds its contents.

1
2
infoField.defaultTextFormat = textformat;
3
infoField.embedFonts = true; //You have to add this to use the embedded font

4
infoField.antiAliasType = AntiAliasType.ADVANCED; //This property will display the text more clearly

5
infoField.width = images[i].width - 5;
6
infoField.height = 20;
7
8
infoField.text = imagesTitle[i]; //The content, obtained from the XML and stored in the Array

Step 19: Resizing the Images

Here we set the desired scale of the images. Since everything will be inside the Container Sprite, we only need to resize it.

1
2
container.scaleX = 0.3;
3
container.scaleY = 0.3;

Step 20: Position

The images will have a random position based on the center of the Stage area. We use Math for that.

1
2
container.x = stage.stageWidth / 4 + Math.floor(Math.random() * (stage.stageWidth / 4));
3
container.y = stage.stageHeight / 5 + Math.floor(Math.random() * (stage.stageHeight / 5));

Step 21: Shadow Filter

This will create a Shadow Filter.

1
2
var shadowFilter:BitmapFilter = new DropShadowFilter(3, 90, 0x252525, 1, 2, 2, 1, 15); //Distance, angle, color, alpha, blur, strength, quality

3
var filterArray:Array = [shadowFilter];
4
5
container.filters = filterArray; //Apply the filter

Step 22: Adding to Stage

Time to add the Children, the order in which we add them is the order they will take in the Display List, so be sure to add them in this way.

1
2
infoArea.addChild(infoField); //Adds the TextField to the TextField Background

3
4
container.addChild(frame); //Adds the Frame to the Container

5
container.addChild(images[i]); //Adds the Image on top of the Frame in the Container

6
7
infoArea.visible = false; //We set the image information to invisible by default

8
9
container.addChild(infoArea); //Adds the information area in top of everything

Step 23: Listeners

Although we could add the Listeners to every Sprite before, I'm going to add them now that they are inside the Container to show you how the Display List works.

flash shuffle photo galleryflash shuffle photo galleryflash shuffle photo gallery
1
2
container.getChildAt(1).addEventListener(MouseEvent.MOUSE_UP, zoomHandler); //This is the Image loaded by the XML, this is the Loader object

3
container.getChildAt(0).addEventListener(MouseEvent.MOUSE_DOWN, dragImage); //This is the Frame

4
container.getChildAt(0).addEventListener(MouseEvent.MOUSE_UP, stopDragImage); //Frame

5
6
addChild(container); //Lastly, we add the Container to the Stage

Step 24: Drag Functions

In the previous step we added two listeners to the Frame of the images. These functions will take care of the drag.

We use "parent" beacuse we want to drag all the objects, since the "target" is the Frame Sprite, the parent object is the Container.

1
2
private function dragImage(e:MouseEvent):void
3
{
4
	e.target.parent.startDrag();
5
}
6
7
private function stopDragImage(e:MouseEvent):void
8
{
9
	e.target.parent.stopDrag();
10
}

Step 25: Zoom

This function is in charge of zooming in and out. Its Listener is in the actual image, so clicking in the Frame will not call this function.

Editor's Note: For some reason, the else if () statement within this zoomHandler function was making our syntax highlighter crash. As it doesn't want to display on the page, I've made the function available for download. Sorry for any inconvenience, Ian.

Step 26: Motion Finish

Some actions need to be executed when the Tweens are finished, these are those actions.

1
2
private function zoomInFinished(e:TweenEvent):void
3
{
4
	zoomed = true; //Modify the variables according to the event

5
	canClick = true;
6
	tween.obj.getChildAt(2).visible = true; //Sets the Information area to visible

7
}
8
9
private function zoomOutFinished(e:TweenEvent):void
10
{
11
	zoomed = false;
12
	removeChild(screen); //Removes the black screen

13
14
	tween.obj.getChildAt(0).addEventListener(MouseEvent.MOUSE_DOWN, dragImage); //Adds the drag listener back to the Frame Sprite

15
}

Step 27: Document Class

Go back to the FLA and add Main as the Document Class in the Properties Panel. If you save your class in a package you have to add the name of the package too, something like: yourpackage.Main

Test your file and see your gallery working!

Conclusion

As always, try different things in your code to make the gallery just as you want.

I hope you enjoyed this tut, thanks for reading!

Advertisement
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.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.