Packagecom.greensock.loading
Classpublic class ImageLoader
InheritanceImageLoader Inheritance DisplayObjectLoader Inheritance LoaderItem Inheritance LoaderCore Inheritance flash.events.EventDispatcher

Loads an image file (png, jpg, or gif) and automatically applies smoothing by default.

The ImageLoader's content refers to a ContentDisplay (Sprite) that is created immediately so that you can position/scale/rotate it or add ROLL_OVER/ROLL_OUT/CLICK listeners before (or while) the image loads. Use the ImageLoader's content property to get the ContentDisplay Sprite, or use the rawContent property to get the actual Bitmap. If a container is defined in the vars object, the ContentDisplay will immediately be added to that container).

If you define a width and height, it will draw a rectangle in the ContentDisplay so that interactive events fire appropriately (rollovers, etc.) and width/height/bounds get reported accurately. This rectangle is invisible by default, but you can control its color and alpha with the bgColor and bgAlpha properties. When the image loads, it will be added to the ContentDisplay at index 0 with addChildAt() and scaled to fit the width/height according to the scaleMode. These are all optional features - you do not need to define a width or height in which case the image will load at its native size. See the list below for all the special properties that can be passed through the vars parameter but don't let the list overwhelm you - these are all optional and they are intended to make your job as a developer much easier.

[new in version 1.89:] When you load() an ImageLoader, it will automatically check to see if another ImageLoader exists with a matching url that has already finished loading. If it finds one, it will copy that BitmapData to use in its own Bitmap in order to maximize performance and minimize memory usage. After all, why load the file again if you've already loaded it? (The exception, of course, is when the ImageLoader's noCache is set to true.)

By default, the ImageLoader will attempt to load the image in a way that allows full script access. However, if a security error is thrown because the image is being loaded from another domain and the appropriate crossdomain.xml file isn't in place to grant access, the ImageLoader will automatically adjust the default LoaderContext so that it falls back to the more restricted mode which will have the following effect:

To maximize the likelihood of your image loading without any security problems, consider taking the following steps:

OPTIONAL VARS PROPERTIES

The following special properties can be passed into the ImageLoader constructor via its vars parameter which can be either a generic object or an ImageLoaderVars object:

Note: Using a ImageLoaderVars instance instead of a generic object to define your vars is a bit more verbose but provides code hinting and improved debugging because it enforces strict data typing. Use whichever one you prefer.

Jerky animation? If you animate the image after loading it and you notice that the movement is rather jerky, try setting the scaleX and/or scaleY to something other than 1, like 1.001 because there is a bug in Flash that forces Bitmaps to always act like their pixelSnapping is "auto" when their scaleX/scaleY are 1.

content data type: com.greensock.loading.display.ContentDisplay (a Sprite). When the image has finished loading, the rawContent will be added to the ContentDisplay Sprite at index 0 using addChildAt(). rawContent will be a flash.display.Bitmap unless unless script access is denied in which case it will be a flash.display.Loader (to avoid security errors).

Example AS3 code:
 import com.greensock.*;
 import com.greensock.events.LoaderEvent;
 import com.greensock.loading.*;
 
 //create an ImageLoader:
 var loader:ImageLoader = new ImageLoader("img/photo1.jpg", {name:"photo1", container:this, x:180, y:100, width:200, height:150, scaleMode:"proportionalInside", centerRegistration:true, onComplete:onImageLoad});
 
 //begin loading
 loader.load();
 
 //when the image loads, fade it in from alpha:0 using TweenLite
 function onImageLoad(event:LoaderEvent):void {
     TweenLite.from(event.target.content, 1, {alpha:0});
 }
 
 //Or you could put the ImageLoader into a LoaderMax. Create one first...
 var queue:LoaderMax = new LoaderMax({name:"mainQueue", onProgress:progressHandler, onComplete:completeHandler, onError:errorHandler});
 
 //append the ImageLoader and several other loaders
 queue.append( loader );
 queue.append( new XMLLoader("xml/doc.xml", {name:"xmlDoc", estimatedBytes:425}) );
 queue.append( new SWFLoader("swf/main.swf", {name:"mainClip", estimatedBytes:3000, container:this, autoPlay:false}) );
 
 //start loading
 queue.load();
 
 function progressHandler(event:LoaderEvent):void {
     trace("progress: " + queue.progress);
 }
 
 function completeHandler(event:LoaderEvent):void {
      trace(event.target + " is complete!");
 }
 
 function errorHandler(event:LoaderEvent):void {
     trace("error occured with " + event.target + ": " + event.text);
 }
 
 

NOTES / TIPS:

Copyright 2010-2013, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for Club GreenSock members, the software agreement that was issued with the membership.

See also

com.greensock.loading.data.ImageLoaderVars


Public Properties
 PropertyDefined By
 InheritedauditedSize : Boolean
[read-only] Indicates whether or not the loader's bytesTotal value has been set by any of the following: Defining an estimatedBytes in the vars object passed to the constructor Calling auditSize() and getting a response (an error is also considered a response) When a LoaderMax instance begins loading, it will automatically force a call to auditSize() for any of its children that don't have an estimatedBytes defined.
LoaderCore
 InheritedautoDispose : Boolean
When autoDispose is true, the loader will be disposed immediately after it completes (it calls the dispose() method internally after dispatching its COMPLETE event).
LoaderCore
 InheritedbytesLoaded : uint
[read-only] Bytes loaded
LoaderCore
 InheritedbytesTotal : uint
[read-only] Total bytes that are to be loaded by the loader.
LoaderCore
 Inheritedcontent : *
[override] [read-only] A ContentDisplay object (a Sprite) that will contain the remote content as soon as the INIT event has been dispatched.
DisplayObjectLoader
 InheriteddefaultAutoForceGC : Boolean = true
[static] By default, LoaderMax will automatically attempt to force garbage collection when a SWFLoader or ImageLoader is unloaded or cancelled but if you prefer to skip this measure, set defaultAutoForceGC to false.
DisplayObjectLoader
 InheritedhttpStatus : int
[read-only] The httpStatus code of the loader.
LoaderItem
 InheritedloadTime : Number
[read-only] The number of seconds that elapsed between when the loader began and when it either completed, failed, or was canceled.
LoaderCore
 Inheritedname : String
A name that you use to identify the loader instance.
LoaderCore
 Inheritedpaused : Boolean
If a loader is paused, its progress will halt and any LoaderMax instances to which it belongs will either skip over it or stop when its position is reached in the queue (depending on whether or not the LoaderMax's skipPaused property is true).
LoaderCore
 Inheritedprogress : Number
[read-only] A value between 0 and 1 indicating the overall progress of the loader.
LoaderCore
 InheritedrawContent : *
[read-only] The raw content that was successfully loaded into the content ContentDisplay Sprite which varies depending on the type of loader and whether or not script access was denied while attempting to load the file: ImageLoader with script access granted: flash.display.Bitmap ImageLoader with script access denied: flash.display.Loader SWFLoader with script access granted: flash.display.DisplayObject (the swf's root) SWFLoader with script access denied: flash.display.Loader (the swf's root cannot be accessed because it would generate a security error)
DisplayObjectLoader
 Inheritedrequest : URLRequest
[read-only] The URLRequest associated with the loader.
LoaderItem
 InheritedscriptAccessDenied : Boolean
[read-only] If the loaded content is denied script access (because of security sandbox restrictions, a missing crossdomain.xml file, etc.), scriptAccessDenied will be set to true.
LoaderItem
 Inheritedstatus : int
[read-only] Integer code indicating the loader's status; options are LoaderStatus.READY, LoaderStatus.LOADING, LoaderStatus.COMPLETED, LoaderStatus.PAUSED, and LoaderStatus.DISPOSED.
LoaderCore
 Inheritedurl : String
The url from which the loader should get its content.
LoaderItem
 Inheritedvars : Object
An object containing optional configuration details, typically passed through a constructor parameter.
LoaderCore
Public Methods
 MethodDefined By
  
ImageLoader(urlOrRequest:*, vars:Object = null)
Constructor
ImageLoader
 Inherited
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
[override]
LoaderCore
 Inherited
auditSize():void
[override] Attempts loading just enough of the content to accurately determine the bytesTotal in order to improve the accuracy of the progress property.
DisplayObjectLoader
 Inherited
cancel():void
If the loader is currently loading (status is LoaderStatus.LOADING), it will be canceled immediately and its status will change to LoaderStatus.READY.
LoaderCore
 Inherited
dispose(flushContent:Boolean = false):void
Disposes of the loader and releases it internally for garbage collection.
LoaderCore
 Inherited
load(flushContent:Boolean = false):void
Loads the loader's content, optionally flushing any previously loaded content first.
LoaderCore
 Inherited
pause():void
Pauses the loader immediately.
LoaderCore
 Inherited
prioritize(loadNow:Boolean = true):void
Immediately prioritizes the loader inside any LoaderMax instances that contain it, forcing it to the top position in their queue and optionally calls load() immediately as well.
LoaderCore
 Inherited
resume():void
Unpauses the loader and resumes loading immediately.
LoaderCore
 Inherited
toString():String
[override] Returns information about the loader, like its type, its name, and its url (if it has one).
LoaderCore
 Inherited
unload():void
Removes any content that was loaded and sets bytesLoaded back to zero.
LoaderCore
Protected Methods
 MethodDefined By
 Inherited
DisplayObjectLoader
 Inherited
[override]
DisplayObjectLoader
  
_load():void
[override]
ImageLoader
Events
 Event Summary Defined By
 InheritedDispatched when the loader is canceled while loading which can occur either because of a failure or when a sibling loader is prioritized in a LoaderMax queue.LoaderCore
 InheritedDispatched when the loader completes.LoaderCore
 InheritedDispatched when the loader experiences some type of error, like a SECURITY_ERROR or IO_ERROR.LoaderCore
 InheritedDispatched when the loader fails.LoaderCore
 InheritedDispatched when the loader experiences an IO_ERROR while loading or auditing its size.LoaderItem
 InheritedDispatched when the loader starts loading.LoaderCore
 InheritedDispatched each time the bytesLoaded value changes while loading (indicating progress).LoaderCore
 InheritedDispatched when the loader unloads (which happens when either unload() or dispose(true) is called or if a loader is canceled while in the process of loading).LoaderCore
Constructor Detail
ImageLoader()Constructor
public function ImageLoader(urlOrRequest:*, vars:Object = null)

Constructor

Parameters
urlOrRequest:* — The url (String) or URLRequest from which the loader should get its content
 
vars:Object (default = null) — An object containing optional configuration details. For example: new ImageLoader("img/photo1.jpg", {name:"photo1", container:this, x:100, y:50, alpha:0, onComplete:completeHandler, onProgress:progressHandler}).

The following special properties can be passed into the constructor via the vars parameter which can be either a generic object or an ImageLoaderVars object:

  • name : String - A name that is used to identify the ImageLoader instance. This name can be fed to the LoaderMax.getLoader() or LoaderMax.getContent() methods or traced at any time. Each loader's name should be unique. If you don't define one, a unique name will be created automatically, like "loader21".
  • container : DisplayObjectContainer - A DisplayObjectContainer into which the ContentDisplay Sprite should be added immediately.
  • smoothing : Boolean - When smoothing is true (the default), smoothing will be enabled for the image which typically leads to much better scaling results (otherwise the image can look crunchy/jagged). If your image is loaded from another domain where the appropriate crossdomain.xml file doesn't grant permission, Flash will not allow smoothing to be enabled (it's a security restriction).
  • width : Number - Sets the ContentDisplay's width property (applied before rotation, scaleX, and scaleY).
  • height : Number - Sets the ContentDisplay's height property (applied before rotation, scaleX, and scaleY).
  • centerRegistration : Boolean - if true, the registration point will be placed in the center of the ContentDisplay which can be useful if, for example, you want to animate its scale and have it grow/shrink from its center.
  • scaleMode : String - When a width and height are defined, the scaleMode controls how the loaded image will be scaled to fit the area. The following values are recognized (you may use the com.greensock.layout.ScaleMode constants if you prefer):
    • "stretch" (the default) - The image will fill the width/height exactly.
    • "proportionalInside" - The image will be scaled proportionally to fit inside the area defined by the width/height
    • "proportionalOutside" - The image will be scaled proportionally to completely fill the area, allowing portions of it to exceed the bounds defined by the width/height.
    • "widthOnly" - Only the width of the image will be adjusted to fit.
    • "heightOnly" - Only the height of the image will be adjusted to fit.
    • "none" - No scaling of the image will occur.
  • hAlign : String - When a width and height is defined, the hAlign determines how the image is horizontally aligned within that area. The following values are recognized (you may use the com.greensock.layout.AlignMode constants if you prefer):
    • "center" (the default) - The image will be centered horizontally in the area
    • "left" - The image will be aligned with the left side of the area
    • "right" - The image will be aligned with the right side of the area
  • vAlign : String - When a width and height is defined, the vAlign determines how the image is vertically aligned within that area. The following values are recognized (you may use the com.greensock.layout.AlignMode constants if you prefer):
    • "center" (the default) - The image will be centered vertically in the area
    • "top" - The image will be aligned with the top of the area
    • "bottom" - The image will be aligned with the bottom of the area
  • crop : Boolean - When a width and height are defined, setting crop to true will cause the image to be cropped within that area (by applying a scrollRect for maximum performance). This is typically useful when the scaleMode is "proportionalOutside" or "none" so that any parts of the image that exceed the dimensions defined by width and height are visually chopped off. Use the hAlign and vAlign special properties to control the vertical and horizontal alignment within the cropped area.
  • x : Number - Sets the ContentDisplay's x property (for positioning on the stage).
  • y : Number - Sets the ContentDisplay's y property (for positioning on the stage).
  • scaleX : Number - Sets the ContentDisplay's scaleX property.
  • scaleY : Number - Sets the ContentDisplay's scaleY property.
  • rotation : Number - Sets the ContentDisplay's rotation property.
  • alpha : Number - Sets the ContentDisplay's alpha property.
  • visible : Boolean - Sets the ContentDisplay's visible property.
  • blendMode : String - Sets the ContentDisplay's blendMode property.
  • bgColor : uint - When a width and height are defined, a rectangle will be drawn inside the ContentDisplay Sprite immediately in order to ease the development process. It is transparent by default, but you may define a bgAlpha if you prefer.
  • bgAlpha : Number - Controls the alpha of the rectangle that is drawn when a width and height are defined.
  • context : LoaderContext - To control whether or not a policy file is checked (which is required if you're loading an image from another domain and you want to use it in BitmapData operations), define a LoaderContext object. By default, the policy file will be checked when running remotely, so make sure the appropriate crossdomain.xml file is in place. See Adobe's LoaderContext documentation for details and precautions.
  • estimatedBytes : uint - Initially, the loader's bytesTotal is set to the estimatedBytes value (or LoaderMax.defaultEstimatedBytes if one isn't defined). Then, when the loader begins loading and it can accurately determine the bytesTotal, it will do so. Setting estimatedBytes is optional, but the more accurate the value, the more accurate your loaders' overall progress will be initially. If the loader will be inserted into a LoaderMax instance (for queue management), its auditSize feature can attempt to automatically determine the bytesTotal at runtime (there is a slight performance penalty for this, however - see LoaderMax's documentation for details).
  • alternateURL : String - If you define an alternateURL, the loader will initially try to load from its original url and if it fails, it will automatically (and permanently) change the loader's url to the alternateURL and try again. Think of it as a fallback or backup url. It is perfectly acceptable to use the same alternateURL for multiple loaders (maybe a default image for various ImageLoaders for example).
  • noCache : Boolean - If true, a "gsCacheBusterID" parameter will be appended to the url with a random set of numbers to prevent caching (don't worry, this info is ignored when you LoaderMax.getLoader() or LoaderMax.getContent() by url or when you're running locally)
  • requireWithRoot : DisplayObject - LoaderMax supports subloading, where an object can be factored into a parent's loading progress. If you want LoaderMax to require this ImageLoader as part of its parent SWFLoader's progress, you must set the requireWithRoot property to your swf's root. For example, var loader:ImageLoader = new ImageLoader("photo1.jpg", {name:"image1", requireWithRoot:this.root});
  • allowMalformedURL : Boolean - Normally, the URL will be parsed and any variables in the query string (like "?name=test&state=il&gender=m") will be placed into a URLVariables object which is added to the URLRequest. This avoids a few bugs in Flash, but if you need to keep the entire URL intact (no parsing into URLVariables), set allowMalformedURL:true. For example, if your URL has duplicate variables in the query string like http://www.greensock.com/?c=S&c=SE&c=SW, it is technically considered a malformed URL and a URLVariables object can't properly contain all the duplicates, so in this case you'd want to set allowMalformedURL to true.
  • autoDispose : Boolean - When autoDispose is true, the loader will be disposed immediately after it completes (it calls the dispose() method internally after dispatching its COMPLETE event). This will remove any listeners that were defined in the vars object (like onComplete, onProgress, onError, onInit). Once a loader is disposed, it can no longer be found with LoaderMax.getLoader() or LoaderMax.getContent() - it is essentially destroyed but its content is not unloaded (you must call unload() or dispose(true) to unload its content). The default autoDispose value is false.

    ----EVENT HANDLER SHORTCUTS----

  • onOpen : Function - A handler function for LoaderEvent.OPEN events which are dispatched when the loader begins loading. Make sure your onOpen function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent).
  • onInit : Function - A handler function for LoaderEvent.INIT events which are called when the image has downloaded and has been placed into the ContentDisplay Sprite. Make sure your onInit function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent).
  • onProgress : Function - A handler function for LoaderEvent.PROGRESS events which are dispatched whenever the bytesLoaded changes. Make sure your onProgress function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent). You can use the LoaderEvent's target.progress to get the loader's progress value or use its target.bytesLoaded and target.bytesTotal.
  • onComplete : Function - A handler function for LoaderEvent.COMPLETE events which are dispatched when the loader has finished loading successfully. Make sure your onComplete function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent).
  • onCancel : Function - A handler function for LoaderEvent.CANCEL events which are dispatched when loading is aborted due to either a failure or because another loader was prioritized or cancel() was manually called. Make sure your onCancel function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent).
  • onError : Function - A handler function for LoaderEvent.ERROR events which are dispatched whenever the loader experiences an error (typically an IO_ERROR or SECURITY_ERROR). An error doesn't necessarily mean the loader failed, however - to listen for when a loader fails, use the onFail special property. Make sure your onError function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent).
  • onFail : Function - A handler function for LoaderEvent.FAIL events which are dispatched whenever the loader fails and its status changes to LoaderStatus.FAILED. Make sure your onFail function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent).
  • onIOError : Function - A handler function for LoaderEvent.IO_ERROR events which will also call the onError handler, so you can use that as more of a catch-all whereas onIOError is specifically for LoaderEvent.IO_ERROR events. Make sure your onIOError function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent).
  • onHTTPStatus : Function - A handler function for LoaderEvent.HTTP_STATUS events. Make sure your onHTTPStatus function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent). You can determine the httpStatus code using the LoaderEvent's target.httpStatus (LoaderItems keep track of their httpStatus when possible, although certain environments prevent Flash from getting httpStatus information).
  • onSecurityError : Function - A handler function for LoaderEvent.SECURITY_ERROR events which onError handles as well, so you can use that as more of a catch-all whereas onSecurityError is specifically for SECURITY_ERROR events. Make sure your onSecurityError function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent).
  • onScriptAccessDenied : Function - A handler function for LoaderEvent.SCRIPT_ACCESS_DENIED events which are dispatched when the image is loaded from another domain and no crossdomain.xml is in place to grant full script access for things like smoothing or BitmapData manipulation. You can also check the loader's scriptAccessDenied property after the image has loaded. Make sure your function accepts a single parameter of type LoaderEvent (com.greensock.events.LoaderEvent).

See also

Method Detail
_load()method
override protected function _load():void