Create an Image Gallery using Flash ActionScript 3.0 and XML

Today you will learn basics of how to create an Image Gallery using Flash Actionscript 3.0 and XML, how to dispatch events, how to load images trough XML file and much more. In next tutorial I will extend this tutorial by adding more features like next – prev buttons, links or text from XML. Let’s begin


Preview


Settings all files

Create a new ActionScript File and save it as “MainClass.as” (com.fladev.gallery.MainClass) – this will be the main class for our flash file; the package classes extends the Sprite class (since we don’t have a timeline animation). Later we will build other classes for thumbs or big image. Finally create a new AS3 Flash file (590×500px) and open it, so that we have both files opened.


MainMovie

Create a simple design for our gallery – see attached. Also create a new symbol, convert this to MovieClip and give him an instance name called “container” that will represent the container where thumbs will be.


XML

Create a folder “images” and inside of this 2 subfolders “large” – all large images will be here –  and “thumb” with all thumbs. I put 15 images and thumbs in these folder, images with a 500px maxim width and all thumbs 100 x 75px. Then create a new XML file called “gallery.xml” and add some nodes that will contain these thumbs and images:

[as3]
<?xml version="1.0" encoding="UTF-8"?>
<GALLERY>
<image src="images/large/1.jpg" thumb="images/thumb/1.jpg" />
<image src="images/large/2.jpg" thumb="images/thumb/2.jpg" />
…………………………………………………………………………..
<image src="images/large/15.jpg" thumb="images/thumb/15.jpg" />
</GALLERY>
[/as3]

The XML file contain just thumbs and images, in next tutorial wi’ll add more features like content or links.


MainClass.as

Let’s add some constants and variables to load XML content:

[as3]
private var xml:XML;
private var urlLoader:URLLoader;
private static const XML_PATH:String = "gallery.xml"
[/as3]

In constructor function wi’ll create the urlLoader:

[as3]
urlLoader = new URLLoader();
urlLoader.load(new URLRequest(XML_PATH));
urlLoader.addEventListener(Event.COMPLETE, loadXML);
[/as3]

After XML is loaded we use his content in loadXML function:

[as3]
private function loadXML(e:Event):void
{
//display hole content from XML
xml = new XML(e.target.data);
}
[/as3]

Trace xml variable to show the content. Let’s move on second part now, by creating some thumbs.


Thumbs

In main movie draw a rectangle with width 100px and height 75px; then convert this to a MovieClip with name “Thumb” and class “com.fladev.gallery.ThumbClass” (we didn’t create this class yet). Inside of this put a new blank MovieClip with instance name “container” on a new layer. Over this layer, create a new layer an put a mask with same size. The thumbs are ready, we just must create the class for this – “ThumbClass.as”;


ThumbClass.as

Create a new ActionScript File and save it as “ThumbClass.as” (com.fladev.gallery.ThumbClass) – this will be the class for all thumbs; the package classes extends the MovieClip class. Here we will add the thumb image inside and will convert this to button:

[as3]
package com.fladev.gallery
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLRequest;

public class ThumbClass extends MovieClip
{
public var image:String;

//we receive the values from MainClass.as
public function ThumbClass(thumb:String, image:String) {
//set this to button mode
this.buttonMode = true;
this.mouseChildren = false;

//store the image path
this.image = image;

//create a loader for image
var loader:Loader = new Loader();
loader.load(new URLRequest(thumb));
this.container.addChild(loader);
}

}

}
[/as3]

Next, let’s add some thumbs on stage.


Adding thumbs

In main movie drag and drop the blank container from library to the stage, give him instance name “container” and center this in middle of stage – this will be the container for thumbs. In MainClass.as add some variables:

[as3]
private var thumbsLength:Number;
private var thumb:ThumbClass;
private var thumbWidth:Number = 100;
private var thumbHeight:Number = 75;
[/as3]

Then in function loadXML where we load the XML file we will call the ThumbClass.as to load each thumb image:

[as3]private function loadXML(e:Event):void
{
//display hole content from XML
xml = new XML(e.target.data);
thumbsLength = xml.image.length();
//attach thumbs on stage
for (var i:int = 0; i < thumbsLength; i++) {
thumb = new ThumbClass(xml.image[i].@thumb, xml.image[i].@src);
container.addChild(thumb);

//show thumbs with a nice effect
setTimeout(moveThumbs, 100*(i+1), thumb, Math.round(100 * i), i);

thumb.x = 230;//play with this value
thumb.y = 0;
}
//create a listener to position the thumb’s container in the middle of stage
this.addEventListener(Event.ENTER_FRAME, positionThumbs);
}
[/as3]

We add the thumbs as childrens of “container” MovieClip from stage, then we set all thumbs coordonates from X and Y to 230 – 0 for a nice effect; we create a timer to position each thumb to his right coordonates, position and finally we create a listener that will position the container in middle of stage. If you have a chance to look at the preview, you’ll see that all thumbs are very nice arranged by columns. To do this, create a new variable to control how many columns you want to be:

[as3]
private var numOfColumns:Number = 5;
private var spacer:Number = 1;
[/as3]

Then the “moveThumbs” function that will arrange the thumbs by columns:

[as3]
private function moveThumbs(pic:MovieClip, xDest:Number, i:Number) {
var c:Number = Math.floor((i % numOfColumns) * (thumbWidth + spacer));
var d:Number = Math.floor(i / numOfColumns) * (thumbHeight + spacer);
Tweener.addTween(pic, { x:c, y:d, time:1, transition:"easeOutSine" } );

//if last thumb was added then we remove the listener that position the thumb’s container
if (i == thumbsLength) {
this.removeEventListener(Event.ENTER_FRAME, positionThumbs);
}
}
[/as3]

And the function “positionThumbs” that will position the thumb’s container:

[as3]
private function positionThumbs(e:Event):void
{
container.x = Math.floor((stage.stageWidth * 0.5) – (container.width * 0.5));
container.y = Math.floor((stage.stageHeight * 0.5) – (container.height * 0.5));
}
[/as3]

Phew, a lot of code here. Test your movie and see all thumbs arranged in the middle of stage. Okay, now we need to add a way that when we click on thumbs to open the big image. To do this, we need to create a new movieclip that will store the big image, a new class for this and a listener on thumbs that will trigger that function to open these large images.


Big image

In main movie, as you created the thumb’s MovieClip, repeat that steps only that this will have a new size – 500x500px. Convert the background to a new MovieClip with instance name “bg”, with name “BigImage” and class path to “com.fladev.gallery.ImageClass” then set the coordonates X and Y for container to 6-6 and finally. When this image will be opened, we need a way to close her and to return back to thumbs – you are right, we must create a button that will do this. Draw a rectangle, convert this to MovieClip and give him an instance name “close_btn”. This button will be inside of the “bigImage” symbol, on his bottom side. The big image container should look like in the above image.

ImageClass.as

[as3]
package com.fladev.gallery
{
import caurina.transitions.Tweener;
import flash.display.Loader;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLRequest;

public class ImageClass extends MovieClip
{
private var loader:Loader;

public function ImageClass() {
//make the close_btn button
close_btn.buttonMode = true;
close_btn.mouseChildren = false;
//on press this will hide the image
close_btn.addEventListener(MouseEvent.CLICK, hideImage);
}

public function loadImage(img:String)
{ //this function will be called from MainClass.as, when thumbs are clicked.
var img:String = img;
loader = new Loader();
loader.load(new URLRequest(img));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, showImage);
}

private function showImage(e:Event):void
{
//add image loaded as child to container
if (container.numChildren >= 1) {
container.removeChildAt(0);
}
container.addChild(loader);

//resize the background of image
bg.height = e.target.content.height + 12;
bg.width = e.target.content.width + 12;
//position the button to the bottom side of image
close_btn.y = bg.y + bg.height + 10;
close_btn.x = bg.x + bg.width – close_btn.width;

Tweener.addTween(this, { time:1, transition:"easeInOutQuint", x:Math.floor((stage.stageWidth * 0.5) – (this.width * 0.5)) } );
Tweener.addTween(this, { time:1, transition:"easeInOutQuint", y:Math.floor((stage.stageHeight * 0.5) – (this.height * 0.5)) } );

}
//when button is pressed will trigger a listener from MainClass.as that will hide this.
private function hideImage(e:MouseEvent):void
{
dispatchEvent(new Event(MainClass.HIDE_IMAGE, true));
}
}

}
[/as3]

Now that we create the class for images, in ThumbsClass.as we will put a listener to activate the function that will make the large image visible:

[as3]
this.addEventListener(MouseEvent.CLICK, showImage);
[/as3]

And the “showImage” function :

[as3]
private function showImage(e:MouseEvent):void
{
//trigger the listener from MainClass.as to show the big image
dispatchEvent(new Event(MainClass.SHOW_IMAGE, true));
}
[/as3]

Ok, we are almost done. Let’s create that listeners in MainClass.as that will show/hide the images. Focus on MainClass.as for next minutes.


Hocus pocus…

Create 2 contants in MainClass.as:

[as3]
public static const SHOW_IMAGE:String = "show_big_image";
public static const HIDE_IMAGE:String = "hide_big_image";
[/as3]

Then in constructor function add 2 listeners:

[as3]
this.addEventListener(SHOW_IMAGE, loadImage);
this.addEventListener(HIDE_IMAGE, hideImage);
[/as3]

…show images:

[as3]
private function loadImage(e:Event):void
{
//we make invisible the container with thumbs and then we show the image
Tweener.addTween(container, { alpha:0, transition:"easeOutSine", time:0.5, onComplete: function doHide() {
container.visible = false;
showImage(e.target.image);
}});
}

private function showImage(value:String) {
//position the big image container
bigImage.x = Math.floor((stage.stageWidth * 0.5) – (bigImage.width * 0.5));
bigImage.y = 0 – bigImage.height;

bigImage.visible = true;
bigImage.loadImage(value);
}

[/as3]

…hide images:

[as3]
private function hideImage(e:Event):void {
//hide the big image container and show thumbs container visible back
Tweener.addTween(bigImage, { time:1, transition:"easeInOutQuint", y:Math.floor((stage.stageHeight + 30)), onComplete: function doShow() {
container.visible = true;
Tweener.addTween(container, { alpha:1, transition:"easeOutSine", time:0.5}) }} );

}
[/as3]

Save everything, and let’s recapitulate. We:

  • put images and thumbs in folders
  • add nodes with these in XML file,
  • create a container in middle of stage to hold the thumbs,
  • create the thumb’s container and the images
  • add function to show/hide images.

Hope you learn something from this and I don’t forget anything (you have sources attached too). Thank you for your time, stay tuned until next tutorial.


Twitter Digg Delicious Stumbleupon Technorati Facebook

30 Responses to “Create an Image Gallery using Flash ActionScript 3.0 and XML”

  1. Hello, can you post the original fla file?

  2. Hi, aren’t source files attached?

  3. Hello,
    Thanks. It worked fine with different images.

  4. Hello, can you post the original fla file?

  5. All sources can be found in .zip archive

  6. works fine, thanks mate:)

  7. @toms: you’re welcome

  8. Hi,
    i just tried to rebuild your GREAT tutorial. But now im stucked on a problem..

    Im at the first part, create thumbs:
    i created the ThumbClass.as with folders and the structur which fits to my project(as3 of course).
    I Also copied the movieclips out of your project into mine but if i want to publish, there is an error in the ThumbClass.
    “1119: Access of possibly undefined property container through a reference with static type com.gallery:ThumbClass.”
    I copied the MCs, the declaration should be the same. Any ideas where the problem could be?

    nice work!!

  9. You forgot to copy the movieclip container I think into thumbs movieclip. Check if this exist there.

    R.

  10. good points and the details are more specific than somewhere else, thanks.

    – Norman

  11. You’re welcome Norman. Thank you for your comment

  12. Hi Robert, Great tutorial 🙂

    I’m having a strange problem, I went over everything you said several times, and kept getting errors stating that Flash didn’t understand things like ‘Tweeners’ etc.

    I have done some troubleshooting and reached the stage where I have noticed this:

    If I download the example files, they work absolutely fine, if I open up the example .fla – do absolutely NOTHING to it, but publish it, I get a run of errors and the .swf does nothing.

    Odd huh? Perhaps this needs some kind of plugin I’m missing? I’m using CS5 proper version etc.

  13. Hi Robert thanks for the help!

    I’ve got it all working now, except for one thing, when I click on a thumb the big-image loads up, when I click close it closes, but nothing else happens, i.e. no thumbs appear.

    I’ve checked the code and it’s identical to the tutorial, any ideas?

    I feel bad for all these problems because I actually think it’s a great tutorial

  14. Hmm…download again, something is strange.

  15. Cool galery, simple looking but smooth working. THX!

  16. Wow! Great tutorial Robert.
    I’m a newbie using flash, this is what I’ve been waiting for. Thank you Robert 🙂

  17. You’re welcome 🙂

  18. Hello Dear,

    Is it possible to post description of an image to show together with the large image either at the bottom or at the left-right side.

    Thanks

  19. Hi there, yes it’s possible.

  20. Hi Robert,

    thats a really helpful tutorial,
    unfortunately I get the same problem as Jamie reported on the 16th Jan, the container never reappears
    I noticed that when I compile your source code using CS4 the SWF is slightly smaller. Any thoughts?

  21. Update:
    I’m not sure what the doShow() function is that is called by onComplete: when the big image fades out.
    I replaced this with a new function that handles the container reappearing.

    unfortunately the container tweens in simultaneously with the image tweening out. Got to investigate why.

    Found out CS4 doesn’t like onComplete:function x() but prefers onComplete:x()
    Quirky

  22. There are any errors?

  23. can you kindly post the zip file. I can’t seem to find it. Thank you

  24. hey,
    how to add video into .xml file of adobe flash.

  25. Hello..

    i want to ask how can i insert some text for every picture in action script?or in xml file.How to do?

  26. 1. You need to modify the XML file;
    ;

    2. In “bigImage” MovieClip, create a new TextField, with name “txt”;

    3. In ImageClass.as in
    public function loadImage(img:String), add a new parameter
    public function loadImage(img:String, t:String) {
    txt.text = t;
    ……………
    }

    4. In ThumbClass.as, add a new public variable: public var title:String;
    then modify the line public function ThumbClass(thumb:String, image:String) { in
    public function ThumbClass(thumb:String, image:String, t:String) {

    and add near this.image = image;
    title = t;

    5. In MainClass.as, on line thumb = new ThumbClass(xml.image[i].@thumb, xml.image[i].@src); add new parameter:
    thumb = new ThumbClass(xml.image[i].@thumb, xml.image[i].@src, xml.image[i].@title);

    That’s it. 5 steps 😉

  27. I’ve changed numOfColumns to 4. nothing happens, why?

  28. This should fix the problem of the container not reappearing in CS4.

    private function hideImage(e:Event):void {
    //hide the big image container and show thumbs container visible back
    Tweener.addTween(bigImage, { time:1, transition:”easeInOutQuint”, y:Math.floor((stage.stageHeight + 30)), onComplete: doShow})
    function doShow(){
    container.visible = true;
    Tweener.addTween(container, { alpha:1, transition:”easeOutSine”, time:0.5}) };

    }