I have been saying for a while I wanted to cover a basic technique in Flash CS3 and ActionScript 3. I speak, of course, of loading external content into a Flash file.
By "external content", I mean loading JPGs, GIFs, PNGs and SWFs into the flash file from the web server and not embedding them in the main SWF file.
In AS2, this was done by creating an instance of a MovieClip, and then either loading directly into the MovieClip using loadMovie() or the more powerful MovieClipLoader class (which gave the developer the ability to check the download progress and make progress bars and other preloaders.
ActionScript 3 has added the Loader class which replaces both the loadMovie() method and the MovieClipLoader class. It has removed the need to have an empty MovieClip placed on the stage as a container for loading the images or SWF files.
Here's the Loader's inheritance chain...
Loader > DisplayObjectContainer > InteractiveObject > DisplayObject > EventDispatcher > Object
For those of us non-programmers, this simply means the Loader gains all the properties and methods of the objects in this list. If the DisplayObject has the ability to be added to the stage and made visible, then so does the Loader etc. Because of this we can add the Loader directly to the stage or any other DisplayObjectContainer. (which also includes MovieClips)
Here's our code...
- var imageFile:URLRequest = new URLRequest("spry_logo.png");
- var myImageLoader:Loader = new Loader();
- myImageLoader.load(imageFile);
- addChild(myImageLoader);
Line 1 prepares the address of the file to be loaded
Line 2 creates the variable name and the instance of the Loader
Line 3 uses the Loader instance to load the file from the address in the URLRequest
Line 4 adds the Loader (with it's loaded content) into the stage, making it visible as well.
You would then most likely want to move the image into position by adding the x and y coordinates to the Loader instance myImageLoader.
- myImageLoader.x = 100;
- myImageLoader.y = 150;
If you want to load a new image to replace the old one (say upon clicking a button), you simply change the url of the URLRequest and then reload the loader.
Here is an example of an event handler function that would do this... (this assumes you have a button, and it has added the event listener for the mouse event CLICK)
- function onButtonClicked(e:MouseEvent):void
- {
- imageFile.url = "flash_logo.png";
- myImageLoader.load(imageFile);
- }
For small projects this should not prove much of a problem, but if you are planning on loading hundreds of images or complex, memory heavy, SWFs; this technique could start eating into system resources.
Hopefully Adobe changes this sooner than later.
--Rich
No comments:
Post a Comment