Login | Register
AS3 Photo gallery

AS3 Photo gallery

In this tutorial we will build a photo gallery. We will load the paths to the photos from an xml file and will use the Tweener class to add some nice transitions.

You can download this class from Google Code download Tweener class.

Click the image to see how the final product will look or try the interactive version at the end of this page.

 

1. Create a new file by going to File > New select Flash file (ActionScript 3.0) and click Ok. Save the file as photo_gallery.fla.

2. Select the Rectangle tool set the stroke to none and the fill to #999999 and on the stage draw a rectangle 110 by 110.Select the rectangle hit F8 to convert it to a MovieClip. Set its name to thumb and set the registration point to center and click Ok.

3. Press Ctrl+L to open the Library. Right click on the thumb MovieClip and select Linkage. Select Export to ActionScript checkbox, set the class name to Thumbnail and click Ok. Select the thumb MovieClip from the stage and delete it.

4. Press Ctrl+F7 to open the Components library. Select the UILoader component and drag it to the stage. We will use this component to load the thumbnails. Select the UILoader component from the stage and delete it, we don’t need it on the stage we need it in the Library (make sure that it’s in the library).

5. Go to File > New select ActionScript file and click Ok. We will build the Thumbnail class witch is associated with the thumb MovieClip.

6. Copy and paste the next code Code:

package {
	import flash.display.Sprite;
	import fl.containers.UILoader;
	import caurina.transitions.*;
	import flash.events.MouseEvent;
 
	public class Thumbnail extends Sprite {
		private var nume:String;
		private var url:String;
		private var id:int;
		private var loader:UILoader;
 
		function Thumbnail(source:String,itemNr:int,numeThumb:String):void {
			url = source;
			id = itemNr;
			this.nume = numeThumb;
			drawLoader();
			addEventListener(MouseEvent.MOUSE_OVER,onOver);
			addEventListener(MouseEvent.MOUSE_OUT,onOut);
			scaleThumb();
		}
		private function drawLoader():void {
			loader = new UILoader();
			loader.source = url;
			loader.mouseEnabled = false;
			loader.x = -50;
			loader.y = -50;
			addChild(loader);
 
		}
		private function onOver(event:MouseEvent):void {
			Tweener.addTween(this, {scaleX:1,scaleY:1, time:1, transition:"easeoutelastic"});
			Tweener.addTween(this, {alpha:1, time:1, transition:"easeoutelastic"});
		}
		private function onOut(event:MouseEvent):void {
			Tweener.addTween(this, {scaleX:.9,scaleY:.9, time:1, transition:"easeoutelastic"});
			Tweener.addTween(this, {alpha:.5, time:1, transition:"easeoutelastic"});
		}
		private function scaleThumb():void {
			this.scaleX = .9;
			this.scaleY = .9;
			this.alpha = .5;
		}
	}
}
Save the file as Thumbnail.as.

 

7. Let’s go back to the photo_gallery.fla. Name the first layer actions and insert a new one (Insert>Timeline>Layer) and name it background. In the Property Inspector click on the Size button and set the width: 570, height: 350, frame rate: 30 and click Ok.

 

8. Select the Rectangle tool set the color to black and the stroke to none. On the background layer draw a rectangle, same dimensions like the stage (570, 350) and position it at x: 0, y: 0.

 

9. Select frame 1 from the actions layer and press F9 to open the ActionScript panel. Copy and paste the next code. Code:

import fl.containers.UILoader;
import caurina.transitions.*;
 
//---------loading the external xml file-------
var urlRequest:URLRequest = new URLRequest("pics.xml");
var urlLoader:URLLoader = new URLLoader();
var myXML:XML = new XML();
var xmlList:XMLList;
myXML.ignoreWhitespace = true;
urlLoader.addEventListener(Event.COMPLETE,fileLoaded);
urlLoader.load(urlRequest);
//--------holds the paths to the thumbnails-------
var arrayURL:Array = new Array();
//--------holds the paths to the big photos-------
var arrayName:Array = new Array();
//--------holds the thumbnail objects-------
var holderArray:Array = new Array();
//--------represents the number of collumns-------
var nrColumns:uint = 5;
//-------represents the container of our gallery
var sprite:Sprite = new Sprite();
addChild(sprite);
var thumb:Thumbnail;
//-------- the thumbnails container-------
var thumbsHolder:Sprite = new Sprite();
sprite.addChild(thumbsHolder);
//-------- the photoLoader container-------
var loaderHolder:Sprite = new Sprite();
loaderHolder.graphics.beginFill(0xffffff,1);
loaderHolder.graphics.drawRect(0,0,550,330);
loaderHolder.graphics.endFill();
loaderHolder.x = 1000;
loaderHolder.y = 10;
sprite.addChild(loaderHolder);
//-------- loads the big photo-------
var photoLoader:UILoader = new UILoader();
photoLoader.width = 540;
photoLoader.height = 320;
photoLoader.y = 5;
photoLoader.x = 5;
photoLoader.buttonMode = true;
photoLoader.addEventListener(MouseEvent.CLICK,onClickBack);
loaderHolder.addChild(photoLoader);

/* we loop through the xml file
populate the arrayURL, arrayName and position the thumbnalis */
function fileLoaded(event:Event):void {
	myXML = XML(event.target.data);
	xmlList = myXML.children();
	for (var i:int=0; i<xmlList.length(); i++) {
		var picURL:String = xmlList[ i ].url;
		var picName:String = xmlList[ i ].big_url;
		arrayURL.push(picURL);
		arrayName.push(picName);
		holderArray[ i ] = new Thumbnail(arrayURL[ i ],i,arrayName[ i ]);
		holderArray[ i ].addEventListener(MouseEvent.CLICK,onClick);
		holderArray[ i ].name = arrayName[ i ];
		holderArray[ i ].buttonMode = true;
		if (i<nrColumns) {
			holderArray[ i ].y = 65;
			holderArray[ i ].x = i*110+65;
		} else {
			holderArray[ i ].y = holderArray[ i-nrColumns].y+110;
			holderArray[ i ].x = holderArray[ i-nrColumns].x;
		}
		thumbsHolder.addChild(holderArray[ i ]);
	}
}
//----handles the Click event added to the thumbnails--
function onClick(event:MouseEvent):void {
	photoLoader.source = event.currentTarget.name;
	Tweener.addTween(thumbsHolder, {x:-650, time:1, transition:"easeInElastic"});
	Tweener.addTween(loaderHolder, {x:10, time:1, transition:"easeInElastic"});
	Tweener.addTween(thumbsHolder, {alpha:0, time:1, transition:"linear"});
	Tweener.addTween(loaderHolder, {alpha:1, time:1, transition:"linear"});
}
//----handles the Click event added to the photoLoader----
function onClickBack(event:MouseEvent):void {
	Tweener.addTween(thumbsHolder, {x:0, time:1, transition:"easeInElastic"});
	Tweener.addTween(loaderHolder, {x:1000, time:1, transition:"easeInElastic"});
	Tweener.addTween(thumbsHolder, {alpha:1, time:2, transition:"linear"});
	Tweener.addTween(loaderHolder, {alpha:0, time:2, transition:"linear"});
}

I provide a little comment (the lines that begins with //) for the variables and functions that tells you what they do or represents. If you have problem with the code fill free to ask.

 

10. The structure of the xml file looks like this:

 

<?xml version="1.0" encoding="utf-8"?>
<images>
	<image>
		<url>pics/img_1.png</url>
		<big_url>big_pics/img_1.png</big_url>
	</image>
	<image>
		<url>pics/img_2.png</url>
		<big_url>big_pics/img_2.png</big_url>
	</image>
</images>

 

Where <image></image> represents a new picture in the gallery. The url tag represents the path to the little picture and the big_url tag the path to the big picture. To add your own pictures you will need to modify these paths. Here I provide the tags for only two images, but the final xml file has 15 images. Open your text editor copy and paste the code from above add the rest of <image></image> tags (until 15) and save the file as pics.xml.

11. Let’s setup the structure of the folders. Make a folder and name it photo_gallery. Inside this folder make two new folders, name one pics and the other big_pics. Inside the photo_gallery folder place the photo_gallery.fla, Thumbnail.as, the pics.xml file and the caurina folder. You will obtain this folder (caurina) after downloading the Tweener class. You will need this folder if you want to modify the fla file.

If you placed all the files in the right place, placed the little pictures in the pics folder and the big pictures in the big_pics you can test photo_gallery.fla file by pressing Ctrl+Enter. You should have no problem.

 

This is all. I hope that you enjoyed the tutorial. Until the next time have fun learning Flash! To download the source files for this tutorial, click here.

Make sure JavaScript is turned on. You need to upgrade your Flash Player

 

About Sorin Haidan

I'm a Flash/ActionScript developer residing in Vaslui, Romania. If you have questions, suggestions, doubts about the tutorial don't hesitate to comment. I'm available for freelance work. You can contact me at this email: biochimistu[at] yahoo[dot]com.

Get new stories first

Click to follow us on Twitter!

 

Comments


Posted by mrtomrobinson on 11/28 at 12:37 PM

This is great, thank you! I’m currently getting to grip with AS3 and this tutorial helps a great deal. My only comment would be to use the incorporated AS3 tween device, rather than a third party one.

Thanks again. Tom


Posted by Jens C Brynildsen on 11/28 at 01:09 PM

Hi Tom,
While convenient, the built-in tween engine in Flash is generally not a good choice. Have a look at this comparison http://blog.greensock.com/tweening-speed-test/ but make sure you save anything open in your browser before trying the native Tween class. It’ll crash…

J


Posted by mrtomrobinson on 11/28 at 05:12 PM

Blimey, that is pretty bad. My only question, now that I’ve had time to work with this code - why is it necessary to force the thumbnails to .9 scale? If you remove this the thumbs are too large. I can’t see what is making them .1 larger than the original image size?!

Apart from that, top job!


Posted by Jens C Brynildsen on 11/28 at 08:51 PM

Hehe. Good call. I suspect that Sorin (the author) found it easier to just scale them with code rather than Photoshop? I’ll try to ask Sorin :)


Posted by Jens C Brynildsen on 11/28 at 08:53 PM

Ahh. Correction - he did this so they will display at 1:1 scale when you move the mouse over.

J


Posted by vivid_ultimatum on 12/04 at 11:24 PM

I seem to get a few errors when running this:

Description - 1067: Implicit coercion of a value of type Array to an unrelated type String.

Source - holderArray = new Thumbnail(arrayURL,i,arrayName);

Description - 1067: Implicit coercion of a value of type Thumbnail to an unrelated type Array.

Same source.

And also

Description - 1067: Implicit coercion of a value of type Array to an unrelated type flash.display:DisplayObject.

Source - thumbsHolder.addChild(holderArray);

Any suggestions?
Thankyou.


Posted by Jens C Brynildsen on 12/11 at 11:48 AM

Hi Vivid,
I’m unable to reproduce those errors in either CS3/CS4. They really should compile without any errors? What Flash version are you using?

J


Posted by mrtomrobinson on 12/15 at 02:41 PM

I’ve fiddled with it a lot, but your initial code was extremely useful in getting my site up and running (and helping me figure AS3):

http://www.tomrobinsonphotography.com/

Thank you very much!


Posted by ambergarner on 01/02 at 11:03 PM

This tutorial is great! I have one question though. I’m building a site entirely in flash, and I want the gallery to appear on only one page. However, when I’ve gone to the gallery page and I click away from that page the other page’s content appears below the gallery, which stays no matter what page I click on. Do you know how to fix this?


Posted by _root.Beer on 01/04 at 05:14 AM

vivid, Im getting the same errors. Ive checked everything, and since im a noob with AS, im imagining it’s something very, very small im overlooking.

If anyone has any clues or leads to this problem and what those error messages might be referencing, please help!

btw im using CS3.

Thanks in advance


Posted by _root.Beer on 01/04 at 05:51 AM

ok, so I looked at the source code in the .zip and it’s totally different than the code in this tutorial above. Not sure why, but I copied the source code from the .zip file into my file, and it works.

So all of the above posters who had this work, did you copy the code from here, or from the .zip file?

Just curious.
Anyway, im happy now.


Posted by lowlight on 01/06 at 02:31 PM

Thank you so much for this tutorial m8, it was much helpful for me to understand and walk through creating arrays, actually i have one question what if i want to make the big picture to navigate to another URL instead of going back to the gallery thumbs i tried to figure out but really got lost.

thank you in advance!


Posted by BlueBadger on 02/20 at 11:13 PM

Great tutorial.  The compile error we are all getting are caused by missing subscripts in the second section of the code.  You will get the errors if copy and paste the code.

The code should read

  var picURL:String = xmlList[ i ].url;
  var picName:String = xmlList[ i ].big_url;

and not

  var picURL:String = xmlList.url;
  var picName:String = xmlList.big_url;

likewise when storing the information in holderarray.

  holderArray[ i ] = new Thumbnail(arrayURL[ i ],i,arrayName[ i ]);
  holderArray[ i ].addEventListener(MouseEvent.CLICK,onClick);

etc

Hope this helps.


Posted by Jens C Brynildsen on 02/24 at 10:14 AM

Sorry about this problem. It’s to do with the CMS we use that did some stupid auto-formatting. I should have noticed this earlier. Thanks to @BlueBadger for solving the issue!

J


Posted by dagny311 on 03/24 at 01:16 PM

My errors are a little different.
1120: Access of undefined property Tweener.(four times from the Thumbnail.as)
as well as
Warning: 3594: children is not a recognized method of the dynamic class XML.
and finally
Warning: 3594: length is not a recognized method of the dynamic class XMLList.

I followed the tutorial and after other issues I downloaded the source files and made the changes BlueBadger noted and still no use.  I’m using cs4.  Please keep me from losing my mind. 
Best,
Dagny


Posted by iraji on 05/17 at 08:50 PM

Very nicely done. I would like to use a caption for each image. Could this be added shomehow just below the large image?
Thanks


Posted by xistenze on 06/02 at 01:25 AM

if you are trying to embed this into another site, just add an extra button nearby with the following code (change to suit your page names)
Clear.addEventListener(MouseEvent.CLICK, clickClear);
function clickClear(event:Event):void {
  Tweener.addTween(thumbsHolder, {x:1110, time:1, transition:“easeInElastic”});
  Tweener.addTween(loaderHolder, {x:1110, time:1, transition:“easeInElastic”});
}

hope that helps anyone


Posted by iraji on 06/02 at 11:27 AM

xistenze, how does that code add a “caption” to the large images? The caption would be in the xml file and would have to be dynamically loaded.


Posted by xistenze on 06/03 at 01:15 AM

i was refereing to this post

Posted by ambergarner on 01/02 at 11:03 PM
This tutorial is great! I have one question though. Im building a site entirely in flash, and I want the gallery to appear on only one page. However, when Ive gone to the gallery page and I click away from that page the other pages content appears below the gallery, which stays no matter what page I click on. Do you know how to fix this?


Posted by kyronus on 06/04 at 01:11 AM

Awsomely done ^^ although i have a little noob question: can this gallery be exported to Dreamweaver or is it exclusive for flash? Is there anyway to bypass this?


Posted by rodder on 06/12 at 12:36 PM

I’m having trouble with this line(55) on the code:
holderArray = new Thumbnail(arrayURL,i,arrayName);

When I test the movie, I get:
1136: Incorrect number of arguments.  Expected 0.


Posted by skaradura on 08/19 at 03:12 AM

hello where is file galeria.fla


Posted by bibritz on 09/06 at 06:56 PM

hi I have a problem with this tutorial. I think I did everything like you descriped. But I have in my Flash some error messages.

“1083: Syntax error: comma not expected.”
“1084: Syntaxfehler: rightparen before semicolon necessary.” in line 55
 
“1083: Syntax error: semicolon not expected.” in line 57
 
“1083: Syntax error: xmltagstartend not expected.” in line 83
 
can you help me with this? do you know how I can correct this?


Posted by mcomeaux on 09/12 at 01:55 AM

Hey,
I’m getting the same problems as britz

1083: Syntax error: comma not expected.
1084: Syntaxfehler: rightparen before semicolon necessary. in line 55

1083: Syntax error: semicolon not expected. in line 57

1083: Syntax error: xmltagstartend not expected. in line 83

If possible could an email response be sent
.(JavaScript must be enabled to view this email address)


Posted by mihox02 on 09/18 at 06:21 PM

some 1 can tell me how i can add the name from picture under thumblines,?
tnx:D
BTW good gallery:D


Posted by BrianG on 09/24 at 04:18 AM

this works fine on my system but when i upload to server nothing loads.  what’s up???


Posted by gameiro on 09/26 at 10:22 PM

iam using your photo galery with a grid that on click will change the xml and show a new set of photos but i am having a problem when i change the xml file the thumbs from the previous set photos remain on stage of the flash can you help me ?


Posted by danny wobble on 11/22 at 05:51 PM

Hello, thanks for the tutorial, altho i seem to be having a problem that i think a few others are expiriencing.  Lines 55, 56, 57 and 83.

55:  1084: Syntax error: expecting identifier before comma.      holderArray[ i ] = new Thumbnail(arrayURL,i,arrayName<i>);

56:  1084: Syntax error: expecting rightparen before holderArray.  holderArray[ i ].addEventListener(MouseEvent.CLICK,onClick);

57:  1084: Syntax error: expecting identifier before semicolon.      holderArray[ i ].name = arrayName<i>;

83:  1084: Syntax error: expecting identifier before xmltagstartend.  }</i></i>

When I test the gallery nothing happens at all at the moment, any help is greatley appreciated :D

thanks, Daniel.


Posted by Jens C Brynildsen on 11/23 at 08:11 PM

Sorry about the issues with this code. It’s our CMS that apparently does not like direct Array access :)

The code listings are fixed now. In the ZIP-file Download you can also find the complete source code with the FLA file.

J


Posted by rodneydangerfield on 11/24 at 05:40 PM

Can anyone help me?
How would I go about editing the external .as file as to remove the shaky tweening inbetween the thumbnail and the larger photo.

I just want the larger images to appear without hardly any animation, or none.

Please Help!
I am a novice when it comes to AS3, thanks!


Posted by DesignerHero on 04/06 at 03:34 PM

I was wondering if there were a way to make an associated menu change the .xml files the gallery is linked to?

I’m looking to make a gallery that links to different organizations of images.


Posted by DesignerHero on 04/23 at 05:50 PM

I know this is a little separate from what this gallery covers, but if I added a tag to the XML, how would I get said tag to load in a dynamic text field next to the final image?


Posted by Jens C Brynildsen on 04/23 at 06:48 PM

@DesignerHero It would take too long to explain here, but if you start with something like this tutorial: http://www.kirupa.com/developer/flashcs3/using_xml_as3_pg1.htm

and then set the result from the XML into you textfield like this:

mytextfield.text = songs.track.title.text();

J


Posted by cheeziie on 07/22 at 10:50 AM

Hi

I’m implementing this flash gallery into a JSP file.
but the flash doesn’t work when I open the jsp file in internet.

It doesn’t show the thumbnails and all.
May I know how to solve this?


Posted by hughcrawfs on 11/19 at 04:06 PM

is there a way to get rid of the border around the thumbnails so its just the image showing and maybe move the thumbs so that there is no margin between each thumb. anyones help ASAP would be a great help

thanks….


Posted by krika24 on 03/06 at 12:14 AM

The gallery works great thanks
I do need some help in changing some things please, first, can I add more than 15 thumbs and then maybe add a scroller?
how about adding a preloader to each image, how can I do that?

thank you very much.


Posted by whatdahec on 02/26 at 07:47 AM

Hello my name is Hector Maxwell,

I followed the tutorial and checked all of the coding, changed all my pics to 110pxl by 110pxl. And all I get is a black screen and nothing else. Do you know what it may be? Could my big_pics be too big?


Posted by oomsm on 03/04 at 10:45 PM

Thank you very much for the tutorial. This is my first time working with flash and I’m having a bit of trouble customizing your code. I wanted to double the size of the entire flash doc. Everything is working just fine when I double the sizes except for the thumbnails. The grey rectangle has doubled but the actual small images are all still 110 x 110. Is there an easy way to change these to actually make them display 220 x 220 and space evenly like they were? I appreciate any help!

Submit a comment

Only registered members can comment. Click here to login or here to register