Loading Images with LoaderMax: Load And Track the Progress of Multiple Images.

This movie requires Flash Player 9

I’m pleased to present the first 2 parts of my first series in my Loadermax series. Yes, you read that correctly, or at least I typed it correctly:) We are going to start learning about LoaderMax by walking through a few examples of how to load images with the LoaderMax ImageLoader. In this post we will go through:

  1. Part 1: Loading a single image and tracking its progress
  2. Part 2: Loading multiple images and tracking the total and individual progress

Part 3: Loading multiple images from an XML file will come out in a few days.

I encourage you to sit back and absorb all the content in the videos,text and links provided. The core methods, properties and events of LoaderMax that we are looking at will be used in many of the tutorials that follow.

Enjoy!

Part 1:Load a Single Image and Track its Progress



To load a single external image and get it into your document doesn’t take much work at all.

Here is some sample code

import com.greensock.*;
import com.greensock.loading.*;

var myImage:ImageLoader = new ImageLoader("images/crab.png", {container:this});
myImage.load();

The ImageLoader’s constructor expects 2 parameters:

1: the URL of the image it needs to load

2: a vars object that contains a series of properties and values that will allow you to adjust initial display settings, eventListeners and more. To see all the goodness you can pack in to the vars object consult the ImageLoader documentation.

The container property is very handy for specifying prior to load where your loader’s content should be placed on the display list. You could have a movie clip called gallery_mc on the stage and you could use container:gallery_mc to load an image into that movie clip.

Specifying a container is completely optional. If it is omitted though, you will have to manually add the content of your loader to the display list via addChild(myImage.content) or something similar.

Load and Track the Progress of a Single ImageLoader

To track the progress of an ImageLoader and conveniently target it after load we need to:

1: Import the LoaderEvent and ContentDisplay classes
2: Specify which event handlers and properties to use in the vars object
3: Create the event handler functions

Import LoaderEvent and ContentDisplay

import com.greensock.*;
import com.greensock.loading.*;
import com.greensock.events.LoaderEvent;
import com.greensock.loading.display.ContentDisplay;

The LoaderEvent is necessary to track all the events that take place while an asset is loading. Read LoaderEvent Documentation.

The ContentDisplay Object acts as a container for your loaded content. It is basically a beefed-up Sprite that has some additional methods and properties for resizing and cropping. Read Tip #1 on content v rawContent.

The most important thing to know right now is that an ImageLoader’s content property refers to the ContentDisplay object that contains your loaded image. 99% of the time you will reference and communicate with your loaded image via the content property of the ImageLoader that loaded your image. More on this when we discuss the event listeners.

Specify which Event Handlers and Properties to Assign to the ImageLoader

var myImage:ImageLoader = new ImageLoader("images/crab.png", {container:this, 
								alpha:0, 
								onProgress:progressHandler,
								onComplete:completeHandler});

This system is identical to how you would add callbacks to a TweenLite/Max tween.

*note that we are setting alpha:0 so that the image will be invisible until our onComplete handler (below) fades it in.

Create the completeHandler function

function completeHandler(event:LoaderEvent):void
{
        trace("event: \t" + event);
	trace("event.target: \t" + event.target);
	trace("event.target.content: \t" + event.target.content);
	
	//get a reference to the content of the loader that fired the complete event
	var loadedImage:ContentDisplay = event.target.content;

	TweenLite.to(loadedImage, .5, {alpha:1});

}

Notice that the completeHandler function is expecting event:LoaderEvent. The information contained in that event is very handy. The code above will generate the following traces:

event: [Event type=”childComplete” bubbles=false cancelable=false eventPhase=2]
event.target: ImageLoader ‘loader1’ (images/whale.png)
event.target.content: [object ContentDisplay]

By understanding these 3 objects we can have a very dynamic way of tracking:

  • which event is being fired
  • which ImageLoader is firing the LoaderEvent
  • where the loaded Content will be after it loads

Again, event.target.content refers to the ContentDisplay Object that contains our loaded image. Referencing the content with the loadedImage var makes things cleaner to read.

Create the progressHandler function

function queueProgressHandler(event:LoaderEvent):void
{
	totalProgressBar_mc.bar_mc.scaleX = event.target.progress;
}

The ImageLoader Object has a progress property (value 0-1) that stores the current load progress of its content.

event.target.progress simply refers to the progress of the ImageLoader that fired this event.

you could also do:

totalProgressBar_mc.bar_mc.scaleX = myImage.progress;

but that is less dynamic.

In the video I noted the similarities between the setting up callback functions in a TweenLite tween and in an ImageLoader. The key difference is that an ImageLoader’s event handler function will always receive a LoaderEvent as a parameter.

Part 2: Load Multiple Images

Loading Multiple Images is a breeze once you understand that a LoaderMax is simply a group of loaders. The loader types can be mixed, but we are just using ImageLoaders for now.

LoaderMax gives you the ability to track the load progress of the entire queue of images as well as individual assets in the queue via the event handlers in the vars object:

var queue:LoaderMax = new LoaderMax({maxConnections:1, 
					onProgress:queueProgressHandler,
					onComplete:queueCompleteHandler,
					onChildProgress:imageProgressHandler, 
					onChildComplete:imageCompleteHandler
									});

By using the LoaderMax.append() method we can add multiple ImageLoaders to our LoaderMax queue.
In this example we add a few additional properties to each imageLoader to adjust the size, position and alpha of the loaded content.

queue.append(new ImageLoader("images/whale.png", {container:this, alpha:0, x:0, y:0, estimatedBytes:60000}));
queue.append(new ImageLoader("images/crab.png", {container:this, alpha:0, x:320, y:0, estimatedBytes:90000}));
queue.append(new ImageLoader("images/lobster.png", {container:this, alpha:0, x:0, y:200, estimatedBytes:90000}));
queue.append(new ImageLoader("images/bird.png", {container:this, alpha:0, x:320, y:200, estimatedBytes:60000}));

EstimatedBytes is important so that LoaderMax has a general idea of how it can track the totalProgress of our load. LoaderMax has a built-in auditing system that can do this for you which is VERY accurate but causes a slight delay as it has to check the file size of each asset prior to loading it. Read more about accurately tracking total progress in tip#9.

Finally, to load your asset, call the load() method:

queue.load();

Correction

In the load multiple images video you may have noticed that I set the loadedImage’s alpha to 0 immediately prior to starting my alpha tween in the queueCompleteHandler. There could be a slight risk of the image showing up very briefly before the onComplete event fires. The best practice really would be to set the alpha to 0 in the ImageLoader constructor prior to the image loading. This is how it is done in the files provided.

Part 3: Load Multiple Files with an XMLLoader

COMING VERY SOON.

I don’t want to overload you out of the gates. The source files for using an XML file to store your ImageLoader data are included in the downloads below. I will be creating a new video and tutorial for this very soon, but quite frankly I’ve overwhelmed myself already.

Download the Source Files

snorkl_loaderMaxIntro_files

Additional Resources / Homework

LoaderMax Overview
LoaderMax tips and Tricks
LoaderMax Documentation
ImageLoader Documentation
Rich Shupe’s Video Series on LoaderMax
LoaderEvent
Content Display

Wrap up

I really haven’t begun to scratch the surface of all the options and features that the ImageLoader provides. Hopefully these videos and the supporting text take away some of the mystery surrounding LoaderMax.

Feedback
In addition to your comments and questions about ImageLoaders, how do you like the new “lightBox” video feature?

My videos look best at their native resolution of 1280×720 and I believe the new way of embedding them will give people the easiest access to viewing them in the largest format that their screen supports without getting too big. I know on my 27″ iMac they still look good but the “fullscreen takeover” can be a bit too much.

tip: You can always “right-click” a video while its playing and select “watch on youtube” to view it in a variety of sizes.

Stay tuned. Part 3 is coming soon!

In the near future we will be discussing:

  1. Targeting a loader via getLoader() and getContent()
  2. ScaleModes and Cropping
  3. Adding additional data to ImageLaoders like captions and links
  4. Navigating through a LoaderMax gallery
  5. Loading and Controlling other media types / loaders: SWFLoader, VideoLoader and MP3Loader
  6. and much more!

Carl

New AS3 Code Challenge Coming Soon!

stay tuned on twitter and facebook to be the first to know.

Most recent AS3 Challenge:Bisector

ps. that google+ button on the right is new. not sure if it works. please test:)

Post to Twitter Post to Facebook

This entry was posted in LoaderMax. Bookmark the permalink.
  • always awesome!!!
    i was looking for some tutorials about LoaderMax, specially the ones related with the SWFLoader class…. Thank you so much. i’ll be following closely these series.

  • Hello Felix. Thank you so much for sharing your kind words. I hope the future videos will help you in your projects. SWFLoaders are very similar to ImageLoaders with a few added twists.
    Most importantly when you want to control a swf you use the loader’s rawContent property instead of the content.

    suppose you want to tell a loaded swf to play. you would do something like:
    mySwfLoader.rawContent.play()

    I’ll be getting into some of the SWFLoader tricks in a little while.

    Best,

    carl

  • Merrick Brewer

    I second this comment. Haven’t used LoaderMax yet, as was unsure as how to use it… love the fact that calculating the progress is as simple as “whateverloaded.progress” and none of this total amount loaded divided bytes total multiplied by number of cats in the living room over number of times I’ve eaten sweets this week etc etc etc….

    I’m straying from my point… what I meant was, thank you Carl, have been really looking forward to this series of tutorials.

  • Stacey Reiman

    Hi Carl (you helped me some over on the greensock forum, thanks a lot for that) – I was wondering if the progress event is easy to turn into a preloaded kind of display? Maybe this is already in your files, I’ll have to check them out on the pc later. I was thinking of using this in my slideshows, and was hoping to implement a little spinner or something for external images/swfs so that people with a slow connection don’t think the app is frozen if something doesn’t load immediately.

  • Stacey Reiman

    Sorry should read PRELOADER this iPad autocorrect drives me nuts!

  • yup the files use the loader’s progress to visusally display a preloading bar. I’m sure it will all make sense when you look at the files and watch the videos.

  • and as always I’ve been looking forward to your comments:) gave me a good chuckle. glad you are into this series. LoaderMax is some good stuff.

  • Loadermax is definitely the way forward for loading of assets etc. Coming from a design perspective and not a straight up coder, having all this stuff do the hard work for you makes life so much easier. Recently had to make a video player for a clients website, and not really having a clue, used all the built in flash components. It worked, and the video streamed in etc, but its clunky, the player interface looks like its from the 90’s and is a pain to customise… bit of practice and I think I’ll be building my own in future, and it can then be styled to match the sites UI.. I could go on and on again, but you’ve got a book to write, not read this rambling mess!!!

  • Merrick Brewer

    Oh for f**ks sake…wrong twitter profile… this is a side project…

    I’ll quit before I make a real idiot of myself, and sign off a comment with Tits McGee or something…

    Merrick

  • Torben

    Great as always Carl.
    About the Lightbox video thing. It doesn’t seem to play nicely with iOS. The Lightbox comes up but no video is playing and no controls showing.

  • thanks for the notification. Its just a youtube video. i thought youtube would detect iOS and throw in some html5 friendly thingy. possibly its the shadowbox.js i’m using. unfortunately i have no way of testing. if you can send a link to a site that does something similar and works in iOS let me know.

  • Melissa

    Can loadermax be used to load a youtube video?  I havent had any success with it. Is there some sort of “special” way to do it? How can I embed a youtube video in my flash website? I am so surprised that this embedding thing which is so easy in html isn’t supported  natively by flash. If it is , it must be the best kept secret in flashland coz i havent found anything in the internet via my research.

    Would you be so kind to share the secret to this poor tortured soul?

  • i will have to get back to you on the particulars of why LoaderMax can or can not load youtube videos directly. In general there is a youtube player that needs to act as an intermediary between your flash code and the playback/loading of the actual video file.

    youtube has a very robust AS3 API for loading and controlling youtube content: http://code.google.com/apis/youtube/flash_api_reference.html

    when you embed a youtube video in html you are actually embedding the player and also telling the player which video to load.

  • Merrick Brewer

    Hi kids, 

    I may be laughed out of town for this, but just used SelfLoader to create a preloader for a little slide show, rather than my usual methods for this. I noticed however that the progress bar was a bit jerky. Still worked fine, but wanted something a little smoother. So instead of simply doing progressbar.scaleX=event.target.progess etc, I instead put the progress into a variable, and then used good old tweenMax to scale the X value:

    So I used this:

    var scaling = event.target.progress; TweenMax.to(progressBar, .1, {scaleX:scaling});

    You then get a nice smooth scroll. Ok so its not rocket science, and probably really obvious to the more advanced as3ers out there, but to a relative beginner, I was quite pleased with myself,and thought I should share this with the community. After all, we all have to start somewhere!

  • That’s a great tip. I will be sure to use it at some point. Congrats on using the SelfLoader… You’re getting ahead of me!!
    😉

    -c

    Ps. The xmlloader vid should be up later today.

  • Merrick Brewer

    Why thank you sir! Somehow being ahead of you is a very large stretch of the imagination! I was just looking through the documentation on LoaderMax, which happened to coincide with needing to put a preloader on a job that I did last week, and that lead me to SelfLoader. 

    Interestingly enough, I looked through actionscript on Jacks’ LoaderMax files from the Greensock site, and buried in there is ProgressCircleLite and Max. Not official yet, but yet another awesome time saving progress bar. 

    Anyway, SelfLoader worked like an absolute charm, like all the greensock classes, so will be using that in future without a doubt!

    Looking forward to the XMLLoader vid!!

    Merrick

  • This is a very useful tutorial, I congratulate you. And sorry for english 🙂

  • XaiLo

     My application uses 3 different xml files, the first xml file (the master file which controls a menu system) contains a list of xml files. The second xml file set, also contains a list of xml files, which in turn populates the menu buttons. The menu buttons link to the 3rd and final set of files, which contain links to image files that populate a thumbnail image gallery.
    The master file uses a variable via a function to update a urlrequest to change the menu links and the second set of files update the gallery thumbnails in the same manner.
    The questions I have are these, can I accomplish the same functionality using LoaderMax? Secondly by swaping the gallery file, is it possible to unload and update the thumbnail gallery with new images? If so a brief description on how this could be accomplished would be much appreciated… I know I can pass a variable to LoaderMax, I just can’t figure out how to do it within a function.
    Thanks in advance for any help on this issue. One other thing all my code is contained within the .fla file, and it’s somewhat large.

  • I probably only understand half of what you are stating / asking. the best thing to do would be to try to build a small example file that only allows you to dynamically swap out xml files to load. LoaderMax has built in methods for destroying loaders and removing the loaded content. in short if you got it working without an XMLLoader, you can get it working with an XMLLoader. I would suggest starting small and looking through the LoaderMax and XMLLoader documentation. by unloading the current XMLLoader and loading a new one you should be fine : http://www.greensock.com/as/docs/tween/com/greensock/loading/core/LoaderCore.html#load(). unfortunately there is only so much complexity I can troubleshoot or advise on.

  • XaiLo

    Thanks for your reply, I actually got it to work properly, just a rather silly silly silly oversight on my part.

  • Thank you so much for this! I have teaching myself a crash course in Flash over the last couple of weeks and I have about 3 weeks left to finish a complicated project – this blog is a lifesaver!

  • Qusaitabbal

    Thanks sir. , it’s really useful toturial 

  • cool. you are welcome!

  • MGTH

    yo carl .. thanks again for the help over on active tuts

    can I bug you again for a wee bit of help with the above tut .. I’m trying to get the progress bar to span the width of the browser window .. but can’t work out how to calculate the current width of the browser window and set that as the end x value of the progress bars tween.

    I’m working from the tut code:

    ..

    import com.greensock.*;

    import com.greensock.loading.*;

    import com.greensock.events.LoaderEvent;

    import com.greensock.loading.display.ContentDisplay;

    //make sure none of the bar_mc is showing

    progressBar_mc.bar_mc.scaleX = 0;

    //create a new SWFLoader

    var myImage:SWFLoader = new SWFLoader(“main.swf”, {container:this, 

      alpha:0, 

      onProgress:progressHandler,

      onComplete:completeHandler});

    function progressHandler(event:LoaderEvent):void

    {

    progressBar_mc.bar_mc.scaleX = myImage.progress;

    }

    function completeHandler(event:LoaderEvent):void

    {

    trace(event.target.content);

    //get a reference to the content of the loader that fired the complete event

    var loadedImage:ContentDisplay = event.target.content;

    TweenLite.to(loadedImage, .5, {alpha:1});

    }

    myImage.load();

    ..

    cheers

    rory

  • Sim

     Carl, is there a way to load img from library using loader max ?

  • Sim_

    why my comment was deleted ?

  • Sim_

     nvm xD

  • Hi Sim,
    LoaderMax is for loading external assets. When your swf loads the entire library (only symbols that are placed on the stage or have “export for actionscript” enabled) is already loaded with it so there is no need for additional loading.

  • Sim_

     thx, i dont know why i missed such basic fact.

  • Gav

    I have downloaded ur source files and they dont work :/ 
    I just loaded them into flash and then tested the movie, any suggestions why..?

  • Strange. I just downloaded the zip, opened all the fla files and exported the swfs. No problems at all.
    Can’t imagine why they wouldn’t work for you.
    What exactly isn’t working? Are you getting errors?