AS3 dynamic loading gallery – No XML required!

Problem was given to me to create a dynamic loading gallery that loads different images per page it is located where the number of images is unknown…

Simple theory and bit of code that might be handy.

Solution:

Pass in a flashvar of the folder name of the images.

Make sure the images are named in numerical order.

Load images based on the location of the folder and listen for an error event:

private function loadImages():void
{
     _imageLoader = new Loader();
     _imageLoader.name = "image" + _imageCounter;
     _imageLoader.load(new URLRequest(PATH + _galleryName + "/" + _imageCounter + ".jpg"));
     _imageLoader.contentLoaderInfo.addEventListener(Event.INIT, imageLoadedHandler);
     _imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoadedHandler);
     _imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, imageErrorHandler);
}

An error is then thrown if there is no image name the number after the number of images in the folder. Handle it like so:

private function imageErrorHandler(e:IOErrorEvent):void
{
     trace("no more images");
}

Basically you set a variable named _imageCounter to 1 and then call the loadImages function.

When an image is finised loading, increment _imageCounter and call the function again.

If you want the images loaded in order one by one then do the above on the COMPLETE event of each load, if order is not important and you want to load faster do the above on the INIT event. There is a way to combine speed and order but for now that’s not an issue.

Cheers,
JK

  1. No comments yet.

  1. May 16th, 2012
    Trackback from : Mac Cosmetics