Get $500+ of the best After Effects files, video templates and music for only $20!
Create an Image Rotator in Flash Using XML and ActionScript 3.0

Create an Image Rotator in Flash Using XML and ActionScript 3.0

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 600×300 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:

<?xml version="1.0"?>
<images>
	<image title="Grass 01" src="images/Grass.png" description="Photo by: 100kr on Flickr"/>
	<image title="Deep Impact on Planet Color" src="images/Water.png" description="Photo by: spettacolopuro on Flickr"/>
	<image title="Yosemite: Fall Colours" src="images/Yosemite.png" description="Photo by: tibchris on Flickr"/>
</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).

package
{

	import fl.transitions.Tween;
	import fl.transitions.easing.Strong;
	import fl.transitions.TweenEvent;

	import flash.display.Sprite;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.display.Loader;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFieldAutoSize;
	import flash.text.AntiAliasType;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.events.Event;
	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.

public class ImageRotator extends Sprite
{

Step 10: Declare Variables

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

private var xml:XML; // Stores the xml file info
private var urlLoader:URLLoader; //Loads the url of the xml file
private var imagesVector:Vector.<Loader> = new Vector.<Loader>(); //Stores the images loaded in the Loader object
private var imagesCounter:int = 0;
private var tween:Tween;
private var lastTarget:*; //Gets the last clicked image, in manual transition mode
private var tweening = false;
private var infoCounter:int = 0; //Changes the xml info to display
private var infoPanel:Sprite = new Sprite();
private var titleField:TextField = new TextField();
private var description:TextField = new TextField();
private var titleFormat:TextFormat = new TextFormat();
private var descriptionTF:TextFormat = new TextFormat();
private var timer:Timer;
private var preloader:Preloader = new Preloader(); //The Preloader in the Library
private var added:Boolean; //Checks if the preloader is in stage

private var titleFont:Helvetica = new Helvetica(); //Instantiate Embedded fonts
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).

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

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.

timer = new Timer(interval);

titleFormat.bold = true;
titleFormat.font = titleFont.fontName;
titleFormat.color = 0xFFFFFF;
titleFormat.size = 14;

descriptionTF.font = bitmapFont.fontName;
descriptionTF.color = 0xEEEEEE;
descriptionTF.size = 8;

titleField.defaultTextFormat = titleFormat;
titleField.autoSize = TextFieldAutoSize.LEFT;
titleField.embedFonts = true;
titleField.antiAliasType = AntiAliasType.ADVANCED;

description.defaultTextFormat = descriptionTF;
description.autoSize = TextFieldAutoSize.LEFT;
description.embedFonts = true;

loadXML(xmlPath);
}

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.

private function loadXML(file:String):void
{
	urlLoader = new URLLoader(new URLRequest(file));
	urlLoader.addEventListener(Event.COMPLETE, parseXML);
}

Step 14: Parse the XML File

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

private function parseXML(e:Event):void
{
	xml = new XML(e.target.data);
	loadImages();
}

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.

private function loadImages():void
{
	for (var i:int = 0; i < xml.children().length(); i++)
	{
		var loader:Loader = new Loader();

		loader.load(new URLRequest(xml.children()[i].@src));

		imagesVector.push(loader);

		loader.contentLoaderInfo.addEventListener(Event.COMPLETE, sortImages);

	}
}       

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.

private function sortImages(e:Event):void
{
	imagesCounter++;

	for (var i:int = imagesVector.length - 1; i >= 0; i--) //go backwards...
	{
		addChild(imagesVector[i]); //...so that images at the start of the XML end up at the front
	}

	if (imagesCounter == imagesVector.length) //If all images are loaded
	{
		createInfoPanel();
		timer.addEventListener(TimerEvent.TIMER, autoChange);
		timer.start();
		addPreloader();
		addActions();
	}
}

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.

private function addActions():void
{
	for (var i:int = 0; i < imagesVector.length; i++)//Gets the number of images
	{
		//Sets the listener, changeImage function will be executed when an image is clicked
		imagesVector[i].addEventListener(MouseEvent.MOUSE_UP, changeImage);
	}
}

Step 18: Manual Transition

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

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

	if(added) //Check if the preloader is in stage, if true, removes it, if already removed, nothing happens
	{
		removeChild(preloader);
		added = false;
	}

	if (! tweening) //If a transition is not in progress
	{
		lastTarget = e.target; //Get the clicked image
		tween = new Tween(e.target,"alpha",Strong.easeOut,1,0,1,true); //Start a transition
		tween.addEventListener(TweenEvent.MOTION_FINISH, changeDepth); //The image will change its depth when the transition is done
		tweening = true; //Indicates a transition is in progress

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

		if (infoCounter >= xml.children().length()) //If the infoCounter is grater than the total number of images
		{
			infoCounter = 0; //Reset
			titleField.text = xml.children()[infoCounter]. @ title; //Apply changes to text fields
			description.text = xml.children()[infoCounter]. @ description;
		}
		else
		{
			titleField.text = xml.children()[infoCounter]. @ title; //Apply changes to text fields
			description.text = xml.children()[infoCounter]. @ description;
		}
	}
}

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.

private function changeDepth(e:TweenEvent):void //When the alpha is 0
{
	setChildIndex(lastTarget, 0); //move the image so it is behind the others
	lastTarget.alpha = 1; //Restore its visibility
	tweening = false; //Mark the tween as being complete
}

Step 20: Create Information Panel

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

private function createInfoPanel():void
{
	//Draw a black rectangle with 50% alpha
	infoPanel.graphics.beginFill(0x000000, 0.5);
	infoPanel.graphics.drawRect(0, 0, 600, 50);
	infoPanel.graphics.endFill();

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

	//Position and set the value of the description field
	description.text = xml.children()[infoCounter]. @ description;
	description.x = 7;
	description.y = 22;

	infoPanel.y = 250; //Position this panel in the bottom

	//Add the children
	infoPanel.addChild(titleField);
	infoPanel.addChild(description);

	addChild(infoPanel);
}

Step 21: Handle Automatic Transition

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

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

	lastTarget = imagesVector; //Gets the last image that was tweened
	tween = new Tween(imagesVector,"alpha",Strong.easeOut,1,0,1,true); //Creates an alpha tween

	/* The same actions of the manual transition, change info etc. */

	tween.addEventListener(TweenEvent.MOTION_FINISH, changeDepth);
	tweening = true;

	if (infoCounter >= xml.children().length())
	{
		infoCounter = 0;
		titleField.text = xml.children()[infoCounter]. @ title;
		description.text = xml.children()[infoCounter]. @ description;
	}
	else
	{
		titleField.text = xml.children()[infoCounter]. @ title;
		description.text = xml.children()[infoCounter]. @ description;
	}
}

Step 22: Position the Preloader MovieClip

This chunk of script adds and places the preloader.

private function addPreloader():void
{
	added = true;

	preloader.scaleX = 0.08;
	preloader.scaleY = 0.08;

	preloader.x = (600 - preloader.width/2) - 12;
	preloader.y = (300 - preloader.height/2) - 12;

	addChild(preloader);
}
}
}

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:

import ImageRotator;

var ir:ImageRotator = new ImageRotator("images.xml", 1100);

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!

Add Comment

Discussion 67 Comments

Comment Page 1 of 21 2
  1. cmon says:

    year 2010 still image rotation

  2. Allen Chou says:

    You can never have enough practical XML tutorials. Thanks a lot, Carlos :)

  3. Rômulo says:

    Nice tuto dude.

  4. Kylio says:

    really? another image gallery fed by XML? Is anyone else over this?

    WTF?

  5. David Moreen says:

    That is pretty nice, the images in the demo is a great touch!

  6. Lori says:

    simple animation…but huge codes….

  7. Khaled says:

    Great tut but don’t you think that these examples are all over the web
    same thing loading XML animate fading etc.. how about 3Dtransitions or using some 3D API like papervision3D

  8. Karl Macklin says:

    What’s with the constant loading icon?

    • Ian Yates says:
      Staff

      I suppose a more appropriate visual would have been a countdown to illustrate when the next transition would happen.

      That wasn’t really within the scope of this tut though, so I guess it’s up to anyone who recreates the Image Rotator to make their own mark.

  9. K says:

    for (var i:int = 0; i < imagesVector.length; i++)
    {
    imagesVector.reverse(); //Used to get the same image order as the xml

    addChild(imagesVector[i]);
    }

    this for loop happens every time an image is loaded. i would put that inside the "if" statement below it.

  10. André says:

    I really liked it, it´s very simple, congratulations and thanks a lot!! :D

  11. Bruno says:

    The rotation of the images works kind of weird when you open it by the first time, or when you clean the cache and test it.

  12. Duder Nuder says:

    So many coding for a small animation . GTFO DUDE

  13. marc says:

    if i use more than 3 images it didn`t work correctly!?

  14. Alex says:

    I tried the whole thing out. Everything works just as it needs to work untill i add an extra image in the images folder and put the right info into the xml file.

    If i run the gallery again with the extra image error appears and the images are in wrong place and with the wrong description.

    Error code:

    ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
    at flash.display::DisplayObjectContainer/setChildIndex()
    at ImageRotator/changeDepth()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at fl.transitions::Tween/set time()
    at fl.transitions::Tween/nextFrame()
    at fl.transitions::Tween/onEnterFrame()

    Could you please help me ? I’m not yet good enough with as3 to figure it out myself.

    Best regards

    • Alex says:

      I have stared for hours to my screen to find what went wrong. Finally I found it,

      imagesVector.reverse();

      Stood on the wrong place, it shouldn’t be in the loop. It reversed the code over and over again.

      That’s what went wrong.

      If you place “imagesVector.reverse();” as last element of the function loadImages then the problem is solved.

      Thx for the basic code.

  15. djg says:

    any one know where i can get a really simple code to create a simple auto scrolling gallery, with simple easing in and out between each image. Tried a oman3d.com tutorial in actionscript 2, but when i added more than 22 images it refused to run the tweening and jerked.. http://www.djgriffiths.co.uk for an preview of what i have done..
    any pointers would be great

  16. djg says:

    any one know where i can get a really simple code to create a simple auto scrolling gallery, with simple easing in and out between each image. Tried a oman3d.com tutorial in actionscript 2, but when i added more than 22 images it refused to run the tweening and jerked.. http://www.djgriffiths.co.uk for an preview of what i have done..
    any pointers would be great

    nice tutorial,… not quite what i am after..

  17. Carlos Mir says:

    ayuda soy nuevo en esto ise todo lo que dice aki y no me sale el swf no me sale nada y aparte kiero ke las imagenes esten en una mascara para ke las eskinas esten redondeadas ayudaaa por favorr!!! se los agradeceriaa bastante.

  18. TheChadNC says:

    All that for something that can be done in After Effects in no time? Seems pointless for such a simple rotating gallery.

    • Alex says:

      Pointless for 3 images, not pointless for a number of 100-300 images

      • mel says:

        it would be pointless, but not with this script

        this script loads all the images at once. now imagine how long it would take to load 300 larger images at once ;)

        the preloader in this example should be a real preloader (loads only a few images ahead), not a loading animation..

  19. P says:

    1084: Syntax error: expecting identifier before lessthan.

    Error in line:

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

    flash cs3

  20. luca says:

    Hi everybody, can somebody help me with hit test in game.
    My code:
    var counter:Number = 0;
    var startX:Number;
    var startY:Number;

    speak_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    speak_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
    live_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    live_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
    play_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    play_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
    cook_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    cook_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
    drink_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    drink_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
    listen_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    listen_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
    wear_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    wear_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
    learn_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    learn_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);

    function pickUp(event:MouseEvent):void {
    event.target.startDrag(true);
    reply_txt.text = “”;
    event.target.parent.addChild(event.target);
    startX = event.target.x;
    startY = event.target.y;
    }
    function dropIt(event:MouseEvent):void {
    event.target.stopDrag();
    var myTargetName:String = “target” + event.target.name;
    var myTarget:DisplayObject = getChildByName(myTargetName);
    if (event.target.dropTarget != null && event.target.dropTarget.parent == myTarget){
    reply_txt.text = “Good Job!”;
    event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    event.target.removeEventListener(MouseEvent.MOUSE_UP, dropIt);
    event.target.buttonMode = false;
    event.target.x = myTarget.x;
    event.target.y = myTarget.y;
    counter++;
    } else {
    reply_txt.text = “Try Again!”;
    event.target.x = startX;
    event.target.y = startY;
    }
    if(counter == 8){ //pocet spravnych umiestneni
    reply_txt.text = “Congrats, you’re finished!”;
    }
    }

    speak_mc.buttonMode = true;
    live_mc.buttonMode = true;
    play_mc.buttonMode = true;
    cook_mc.buttonMode = true;
    drink_mc.buttonMode = true;
    listen_mc.buttonMode = true;
    wear_mc.buttonMode = true;
    learn_mc.buttonMode = true;

    I want new tab that show points how many are correct and how many are incorrect.
    I want to add check button with function that show new little window with results (correct and wrong points or answers). Function with counter of correct and incorrect answers.
    Thanks

  21. Funkcje.net says:

    Array.reverse, save a lot of code in this example. BTW you code looks like be written by newbie. :asd

  22. rick says:

    re: The rotating image banner code.
    Thanks for the work and the tut. Works great until I add a 4th image then I get a line 29 error message.
    Was there an update in the code to correct this?
    thanks

  23. rick says:

    Actually to correct the problem with adding another image …
    I commented out /* imagesVector.reverse(); */
    Seems to be working
    thx

    • rick says:

      Hi Carlos (or anyone who cares to help out)
      Thanks for the work. You’re making me think.
      I can run the Instance.swf perfectly locally, but when I uploaded to my ftp, it wont fire up.
      All paths appear to be correct, because I can call up individual pngs.
      Is there something in the code that I have missed? I have been working on this for many hours.
      It’s gotta be something simple I am missing.
      Thanks in advance …
      Rick

  24. ian robson says:

    thankyou so much. Got me to thinking and I was wondering how would you go about adding a link to each image if you wanted to?

  25. Nathan says:

    ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
    at flash.display::DisplayObjectContainer/setChildIndex()
    at ImageRotator/changeDepth()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at fl.transitions::Tween/set time()
    at fl.transitions::Tween/nextFrame()
    at fl.transitions::Tween/onEnterFrame()

    I get this anytime I add a fourth image, whats going wrong?

  26. Milos says:

    I have the same problem! :P Please, give us the working code <3

  27. sean says:

    WOW! that’s mucho code…. I get the above Error #2025, even from the source code without adding any photos. The above tutorial ImageRotator.as code does not match the source download ImageRotator.as code, however, I could not get either to work correctly…other than that…OK…cheers…

  28. Tim Glass says:

    Wow! This is a great tutorial and just what I need for my site. However, when I export (or even cntrl+enter) and run it, the descriptions aren’t with the correct image. Any help?

    thanks,
    Tim

  29. Felix KC says:

    Hey, nice tut and rotator! Is it possible to have more than 3 pictures? I tried 4 pictures and text and pictures didnt sync up. Please answer! Thanks,

  30. kavidu says:

    thanks

  31. JoshuaS says:

    Thanks for the tutorial! This is EXACTLY what I was looking for! However, like many others have stated, the slideshow gets out of sync if I try to add more than 3 images. How do I get around this? I’ve tried the suggestions in the comments with no luck! :(

    Also, how do I change the automatic image transition speed?

    • TimN says:

      To adjust the image transition speed change the “2000″ in this line:

      public function ImageRotator(xmlPath:String = “images.xml”, interval:int = 2000):void

      • blackbball says:

        Hey quick question. Kind of a newby but when I change the “2000″ line in Adobe Dreamweaver how do I get it to apply to the .swf movie file? I keep changing the “2000″ line but yet the .swf movie file doesn’t get any slower.

        Any Help would be appreciated!!
        Thanks!

  32. arun says:

    I want to add http:// link to each image in XM

    can any one solve it.

  33. TimN says:

    Aye, the description, etc breaks upon adding a 4th image. Strange, any fix yet?

  34. nirupam says:

    if i want to just make the images slide from bottom to top with some interval..how will i do that.
    Please,help me do that.

  35. cblack3737 says:

    When I change the Time interval how do i have it apply to the .swf?? I am changing the line with “2000″ in it in Dreamweaver but then how do i make sure that it will then apply to the flash document??

    Thanks!

  36. blackdog says:

    Anyone find a fix for using more than 3 images yet?

    • nocturnal says:

      This should sort the problem of the 3 images and text sync issues. Open up imageRotator.as file and:

      1) Inside the function “sortImages(e:Event):Void” etc, cut the code: imagesVector.reverse();

      2) Locate the “private function loadImages():void” function, go to the last curly bracket at the end of the loadImages function and paste it just above that, so essentially it should be inbetween 2 curly brackets at the end. Save and export and thats it.

      Should sort it out. Thanks to Alex for this fix and thanks to Carlos for this decent banner.

  37. How to use an Array instead of Vector for the 1084: Syntax Error?

  38. Chris says:

    note for all users**

    function SORTIMAGES()

    you will see “”"imagesVector.reverse();”"” in that function this is WRONG

    MOVE to LOADIMAGES() FUNCTION

    and below that last brace at the bottom, which is also known as out side of the FOR LOOP

    paste “”"imagesVector.reverse(); “”"” there

    REMEBER TO SAVE IT AND IT WILL WORK :) :)

    reason im saying this is because reading alexs post was a bit hard to read/understand

  39. Arne says:

    Very nice Image Rotator. Thank you! Is it also possible to switch the images by keys? At the time it only works automatic or by mouse. Can anyone help?

    I tried to insert code – but this doesn’t work:

    /* XML Image Rotator */
    /* Developed by Carlos Yanez */
    /* Creates an XML image gallery or image rotator */

    package
    {

    import fl.transitions.Tween;
    import fl.transitions.easing.Strong;
    import fl.transitions.TweenEvent;

    import flash.display.Sprite;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.display.Loader;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.text.TextFieldAutoSize;
    import flash.text.AntiAliasType;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.events.KeyboardEvent;

    public class ImageRotator extends Sprite
    {
    private var xml:XML;
    private var urlLoader:URLLoader;
    private var imagesVector:Vector. = new Vector.();
    private var imagesCounter:int = 0;
    private var tween:Tween;
    private var lastTarget:*;
    private var tweening = false;
    private var infoCounter:int = 0;
    private var infoPanel:Sprite = new Sprite();
    private var titleField:TextField = new TextField();
    private var description:TextField = new TextField();
    private var titleFormat:TextFormat = new TextFormat();
    private var descriptionTF:TextFormat = new TextFormat();
    private var timer:Timer;
    private var preloader:Preloader = new Preloader();
    private var added:Boolean;

    private var titleFont:Helvetica = new Helvetica();
    private var bitmapFont:Helvetica = new Helvetica();

    public function ImageRotator(xmlPath:String = “images.xml”, interval:int = 5000):void
    {
    timer = new Timer(interval);

    titleFormat.bold = true;
    titleFormat.font = titleFont.fontName;
    titleFormat.color = 0xFFFFFF;
    titleFormat.size = 14;

    descriptionTF.font = bitmapFont.fontName;
    descriptionTF.color = 0xEEEEEE;
    descriptionTF.size = 10;

    titleField.defaultTextFormat = titleFormat;
    titleField.autoSize = TextFieldAutoSize.LEFT;
    titleField.embedFonts = true;
    titleField.antiAliasType = AntiAliasType.ADVANCED;

    description.defaultTextFormat = descriptionTF;
    description.autoSize = TextFieldAutoSize.LEFT;
    description.embedFonts = true;

    loadXML(xmlPath);
    }

    private function loadXML(file:String):void
    {
    urlLoader = new URLLoader(new URLRequest(file));
    urlLoader.addEventListener(Event.COMPLETE, parseXML);
    }

    private function parseXML(e:Event):void
    {
    xml = new XML(e.target.data);

    loadImages();
    }

    private function loadImages():void
    {
    for (var i:int = 0; i < xml.children().length(); i++)
    {
    var loader:Loader = new Loader();

    loader.load(new URLRequest(xml.children()[i].@src));

    imagesVector.push(loader);

    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, sortImages);
    }
    }

    private function sortImages(e:Event):void
    {
    imagesCounter++;

    for (var i:int = 0; i < imagesVector.length; i++)
    {
    //imagesVector.reverse();

    addChild(imagesVector[i]);
    }

    if (imagesCounter == imagesVector.length)
    {
    createInfoPanel();
    timer.addEventListener(TimerEvent.TIMER, autoChange);
    timer.start();
    addPreloader();
    addActions();
    }
    }

    private function addActions():void
    {
    for (var i:int = 0; i = xml.children().length())
    {
    infoCounter = 0;
    titleField.text = xml.children()[infoCounter]. @ title;
    description.text = xml.children()[infoCounter]. @ description;
    }
    else
    {
    titleField.text = xml.children()[infoCounter]. @ title;
    description.text = xml.children()[infoCounter]. @ description;
    }
    }
    }

    private function keyDownHandler(e:KeyboardEvent):void
    {
    timer.stop();

    if(added)
    {
    removeChild(preloader);
    added = false;
    }

    switch(e.keyCode){
    case 37: trace(“Linke Pfeiltaste”); break;
    case 39: trace(“Rechte Pfeiltaste”); break;
    }

    if (! tweening)
    {
    lastTarget = e.target;
    tween = new Tween(e.target,”alpha”,Strong.easeOut,1,0,1,true);
    tween.addEventListener(TweenEvent.MOTION_FINISH, changeDepth);
    tweening = true;

    infoCounter++;

    if (infoCounter >= xml.children().length())
    {
    infoCounter = 0;
    titleField.text = xml.children()[infoCounter]. @ title;
    description.text = xml.children()[infoCounter]. @ description;
    }
    else
    {
    titleField.text = xml.children()[infoCounter]. @ title;
    description.text = xml.children()[infoCounter]. @ description;
    }
    }

    }

    private function changeDepth(e:TweenEvent):void
    {
    setChildIndex(lastTarget, 0);
    lastTarget.alpha = 1;
    tweening = false;
    }

    private function createInfoPanel():void
    {
    infoPanel.graphics.beginFill(0×000000, 0.5);
    infoPanel.graphics.drawRect(0, 0, 550, 40);
    infoPanel.graphics.endFill();

    titleField.text = xml.children()[infoCounter]. @ title;
    titleField.x = 20;
    titleField.y = 5;

    description.text = xml.children()[infoCounter]. @ description;
    description.x = 21;
    description.y = 22;

    infoPanel.y = 360; // Position des Info-Panel auf de y-Achse

    infoPanel.addChild(titleField);
    infoPanel.addChild(description);

    addChild(infoPanel);
    }

    private function autoChange(e:TimerEvent):void
    {
    infoCounter++;

    lastTarget = imagesVector;
    tween = new Tween(imagesVector,”alpha”,Strong.easeOut,1,0,1,true);
    tween.addEventListener(TweenEvent.MOTION_FINISH, changeDepth);
    tweening = true;

    if (infoCounter >= xml.children().length())
    {
    infoCounter = 0;
    titleField.text = xml.children()[infoCounter]. @ title;
    description.text = xml.children()[infoCounter]. @ description;
    }
    else
    {
    titleField.text = xml.children()[infoCounter]. @ title;
    description.text = xml.children()[infoCounter]. @ description;
    }
    }

    private function addPreloader():void
    {
    added = true;

    preloader.scaleX = 0.08;
    preloader.scaleY = 0.08;

    preloader.x = (550 – preloader.width/2) – 25;
    preloader.y = (400 – preloader.height/2) – 10;

    addChild(preloader);
    }
    }
    }

  40. Adam says:

    I did the entire tutorial twice and it didn’t work. I then downloaded your source files and checked my code. That didn’t work either. I tried to load your source files and that didn’t work either. Am I missing a key piece to all of this?

  41. Sandeshaya says:

    Congratulations and thanks a lot!! :D

  42. MetalKid says:

    What if I want to get rid of the infoPanel??? I tried but unsuccessful… I want to display just the banner instead. Thanks..

  43. hthomas says:

    Fab tutorial for real novices like myself.

    How would I rotate the whole slideshow to run though at a slight angle?

  44. Dan says:

    I’ve have a container which is 1000 x 1000.

    I am loading in my images (also 1000×1000) to the Image Rotator and then adding the rotator as a child to my container.

    For some reason the images do not fully fill the container. When I apply the height/width to the images before adding they do not show?

  45. Jane says:

    Hey,

    Very generous of you to provide all this information for free! I also tried to create my own image rotator with the help of this tutorial but unfortunately I couldn’t get it work, and to be honest I just gave it up. I ended up using : this photo rotator, which has some nice text effects and which can be customized as you wish. I wait for your opinions and suggestions :).

  46. Maxim says:

    What does ‘s doing there in 22th position?

  47. Sean says:

    How do I get rid of all the text?

    I just want the pics to change.

  48. Dinesh says:

    Thanks a lot it saved my time

  49. Neal says:

    Is there a ways I can tween the infopanel separate from the image tween? Tweaked it the way I want it up to this point and need to move on with the rest of the website so I can spend any more time on it. So I’m wondering if anyone has any suggestions?

  50. Monica says:

    Hi Carlos-
    If I zip you a file could you show me how to put your image slider onto my home page?

Comment Page 1 of 21 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.