Loading an image into a Movieclip linked to a class in AS 3.0

This article will pick up where we last left off with ‘How do you load an image into a movieclip in AS 3.0?’ If you have not read the previous article, please do so. I will not be covering the creation of the image pod asset in this article. The following example will introduce you to the concept of associating classes with MovieClips. We will be using a main class that will add the image pod to the stage. You will also learn how to create your own preloader by using Flash’s drawing tools.

Example – single pod
First thing we need to do is download the previous files, so we have something to work with.
Once you have unzipped, create a new folder and drag the imageAssetExample.fla from the unarchived folder into your new folder.
While your at it, grab the ‘cherries.jpg’ from the unarchived folder and drop it into your new folder.

Open up imageAssetExample.fla and rename it to imagePodExample.fla.
Open up the Properties Panel and under the Document class dialog you will find the previous class ImageIntoAMovieclipExample, delete, and add the word ‘Main’ to the dialog.
Now open up your text editor of choice and lets create the ‘Main’ document class.
Type:

package{

import flash.display.*;

public class Main extends Sprite{

private var pod:MovieClip;

public function Main():void
{
pod = new ImagePod(“cherries.jpg”);
pod.x = 25;
pod.y = 25;
addChild(pod);
pod.loadImage();
}

}
}

Save it to the same folder as the .fla and name it Main.as.

Lets revisit the code.
At the moment all the logic of the class is in the Main method:

public function Main():void
{
pod = new ImagePod(“cherries.jpg”);
pod.x = 25;
pod.y = 25;
addChild(pod);
pod.loadImage();
}

The Main method is creating, attaching and positioning an imagePod MovieClip to the stage and calling a function named loadImage in the imagePod class which starts the loading of the ‘cherries.jpg’.
There’s really not much to it.
Lets get down to the real action.

Navigate back to the Flash Ide and open up the Library Panel.
Select the imagePod MovieClip Right Click or (Ctrl click MAC) and Select Linkage..
You will find:

propPanel

In the Class dialog revise the current text ‘imagePod’ to read as ‘ImagePod’ and Select OK. Essentially what we are doing here is un-linking the previous Flash generated class and updating the link to point to our soon to be created ImagePod class. Let’s stub that out now, open up your text editor and type:

package{

import flash.display.*;

public class ImagePod extends MovieClip{

public function ImagePod():void
{
}

}

Save as ImagePod.as and make sure its in the same folder as the fla.

Navigate back to the Flash Ide, we are now ready to create our preloader asset.
Open up the Library Panel and double click on the imagePod MovieClip.
Add a New Layer above the ‘mask’ layer and name the New Layer ‘preloader’.

Select the rectangle tool and draw a rectangle (fill only) on the stage (I drew a grey rectangle 100X10pixels).
Select the rectangle, right click (or ctrl click MAC) select Convert to Symbol option.
In the Name dialog enter a name (I entered preloader).
In the Type radio buttons select MovieClip.
Select OK.
Double click on the preloader Movieclip you just made, we should now be in the preloaders timeline.
Select the default layer(the one the vector graphic is on) and label it ‘bar’.
Select the the vector rectangle on stage and right click (or ctrl click MAC) select Convert to Symbol option.
In the Name dialog enter a name (I entered bar).
In the Type radio buttons select MovieClip.
Select OK.
Select the the bar MovieClip on stage and open up the properties panel, give it an instance name of ‘bar’.
That is it for our scaling bar. We now want to spruce it up with an outline so the user can visually measure how much of the requested image has loaded.

Add a New Layer and label it, ‘stroke’.
Select the rectangle tool and draw a rectangle stroke (means no fill) the same size as the bar MovieClip(100X10 pixels);
Position the stroke to be perfectly on top of the bar MovieClip.
There is no need to turn the stroke into a MovieClip, unless you wanted to access it with ActionScript, in our case we don’t.

If you followed the directions correctly you should have this:

stage

Back out of the preloader, so that your in the imagePod timeline, and center your newly created preloader with in your image pod cornered square, it should look like this :

stage_preloader

We could have easily created this simple preloader with Flash’s drawing API. I chose to teach you this method of creation, because as an experienced Flash engineer who work with designers, I always get these elaborate designed preloading assets. It’s rare that I ever get requests for a basic rectangle bar. Later on in the article I’ll show you another method in which an animator can hand off a custom animation for the preloader.

Now that we have all our assets in place let’s proceed with entering the last parts of code that ties this all together.

Navigate back to your ImagePod Class and type:

package{

import flash.display.*;
import flash.events.*;
import flash.net.*;

public class ImagePod extends MovieClip{

private var imgLoader:Loader;
private var imgPath:String;
private var preloadBar:MovieClip;

public function ImagePod(inPath:String):void
{
trace(“IMAGE POD : ” + inPath);
imgPath = inPath;
preloadBar = preloader.bar;
preloadBar.scaleX = 0;
preloader.alpha = 0;

}
public function loadImage():void
{
trace(“loadImage” + imgPath);
preloader.alpha = 1;
imgLoader = new Loader();
imgLoader.contentLoaderInfo.addEventListener(Event.INIT,initImage);
imgLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,onImgLoaded);
imgLoader.load(new URLRequest(imgPath));
}
private function initImage(evt:Event):void
{
trace(“InitImage”);
container.addChild(imgLoader.content);
}
private function onImgLoaded(evt:Event):void {
trace(“onImgLoaded”);
preloader.alpha = 0;
}
private function onProgress(evt:ProgressEvent):void {
var loaded:Number = evt.bytesLoaded;
var total:Number = evt.bytesTotal;
var percLoaded:Number = loaded/total;
preloadBar.scaleX = percLoaded;
trace(“onProgress : ” + percLoaded)
}

}

}

So the first thing you will notice is that we imported a few more flash classes:

import flash.events.*;
import flash.net.*;

The events are pretty obvious, with out these classes we could not add listeners to our image loader.
The net classes are needed to access the URLRequest which actually loads the image into the Flash player.

The next thing we do is add some variables :

private var imgLoader:Loader;
private var imgPath:String;
private var preloadBar:MovieClip;

This is not only good coding practice but it’s the way we reference items, if need be with in the class.
Next you will notice that I fleshed out the constructor method.

public function ImagePod(inPath:String):void
{
trace(”IMAGE POD : ” + inPath);
imgPath = inPath;
preloadBar = preloader.bar;
preloadBar.scaleX = 0;
preloader.alpha = 0;

}

In the function parameters I added a value that must be passed in when constructing a new image pod.
This value is a string path to the image you want to load.
In the next few lines we are setting the preloadBar to equal the actual instance of the preloader’s child bar instance in the image pod Movieclip. We do a little positioning and then we set the preloader instance visibility to be off.

preloadBar = preloader.bar;
preloadBar.scaleX = 0;
preloader.alpha = 0;

Moving forward we add a new method loadImage():

public function loadImage():void
{
trace(”loadImage” + imgPath);
preloader.alpha = 1;
imgLoader = new Loader();
imgLoader.contentLoaderInfo.addEventListener(Event.INIT,initImage);
imgLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,onImgLoaded);
imgLoader.load(new URLRequest(imgPath));
}

We start the method off by changing the visibility of the preloader instance to be on.
We then instantiate a new Loader Object, and we add event listeners to it, then we load. Each listener will call a different method depending on the type of EVENT that is called back from the loader object.

So in the case of INIT we call the initImage method. This basically tells us that the Flash player has control of our loading asset and we can now access some of its properties. In our case we tell the Flash Player that we want it to show up in the ‘container’ instance of our image pod. (load it into our empty MovieClip)

private function initImage(evt:Event):void
{
trace(”InitImage”);
container.addChild(imgLoader.content);
}

The next event we are listening for is the PROGRESS event. This event gives us loading information that we will use to manipulate our preloader. When the event is called we call the onProgress() method

private function onProgress(evt:ProgressEvent):void {
var loaded:Number = evt.bytesLoaded;
var total:Number = evt.bytesTotal;
var percLoaded:Number = loaded/total;
preloadBar.scaleX = percLoaded;
trace(”onProgress : ” + percLoaded)
}

We gather the bytesLoaded and bytesTotal information from the event and do a little math to figure out how much has been loaded. We then assign the value to the preloaderBar x scale.

When the image has loaded the final event is called COMPLETE, which calls the method onImgLoaded().

private function onImgLoaded(evt:Event):void {
trace(”onImgLoaded”);
preloader.alpha = 0;
}

All we do in this method is access the ‘preloader’ instance and turn its visibilty off.

Navigate back to the Flash Ide and COMPILE! Select-Control Test Movie. If all your typing is correct and if you set up your Fla correctly you should see a pod with an image. In Test Movie mode Select-View Simulate Download and you will see the preloader in action. That pretty much covers this article. As promised I’ll cover some more code which will enable you to use an animation instead of the programmatic scaling bar.

Example – animated preloader

Navigate back to the Flash Ide.
Open up the Library Panel and double click on the imagePod MovieClip.
Add a New Layer above the ‘preloader’ layer and name the New Layer ‘preloaderanimation’.
Select the Oval tool and draw a circle (I drew a 10×10 red circle).
Select the circle, right click (or ctrl click MAC) select Convert to Symbol option.
In the Name dialog enter a name (I entered redCircle).
In the Type radio buttons select MovieClip.
Select OK.

Select the circle MovieClip open the properties panel and give it an instance name of preloaderAnimation.
Now double click on the circle MovieClip you just made, we should now be in the circles timeline.
Select the default layer and label it ‘circle’.
For simplicity sake, insert a keyframe (Insert-Timline-Keyframe) on frame 65.
Select the keyframe and open the properties panel and adjust the width and height to be 50.
Select frame #1 right click (ctrl click MAC) ,Select Create Shape Tween.

Add a New Layer and label the layer ‘actions’.
If you followed closely this is what your stage should look like:

circleStage

To complete this animation when need to add code to the timeline.
Select frame #1 in the ‘actions’ layer and open up the Actions panel.
Type:

stop();

Select frame #65 Insert-Timeline-Blank Keyframe. Select the blank keyframe open up the Actions panel.
Type:

stop();

Back out one level so that we are back in the imagePod MovieClip.
Position the circle animation ( I just bumped it up to our scaling preloader).
Navigate back to the ImagePod class and revise the class to control the new circle instance.
The final ImagePod class should look like this :

package{

import flash.display.*;
import flash.events.*;
import flash.net.*;

public class ImagePod extends MovieClip{

private var imgLoader:Loader;
private var imgPath:String;
private var preloadBar:MovieClip;

public function ImagePod(inPath:String):void
{
trace(“IMAGE POD : ” + inPath);
imgPath = inPath;
preloadBar = preloader.bar;
preloadBar.scaleX = 0;
preloader.alpha = 0;
preloaderAnimation.alpha = 0; // new line of code. All we are doing is accessing the instance/MovieClip and hiding it.

}
public function loadImage():void
{
trace(“loadImage” + imgPath);
preloader.alpha = 1;// you may set this value to 0 to hide the scaling preloader
preloaderAnimation.alpha = 1; // we make it (circle) visible here
imgLoader = new Loader();
imgLoader.contentLoaderInfo.addEventListener(Event.INIT,initImage);
imgLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,onImgLoaded);
imgLoader.load(new URLRequest(imgPath));
}
private function initImage(evt:Event):void
{
trace(“InitImage”);
container.addChild(imgLoader.content);
}
private function onImgLoaded(evt:Event):void {
trace(“onImgLoaded”);
preloader.alpha = 0;
preloaderAnimation.alpha = 0; // we hide the circle here.
}
private function onProgress(evt:ProgressEvent):void {
var loaded:Number = evt.bytesLoaded;
var total:Number = evt.bytesTotal;
var percLoaded:Number = loaded/total;
var currentframe:Number = Math.round(preloaderAnimation.totalFrames*percLoaded); //do a little math to figure out which frame we should be on
preloaderAnimation.gotoAndStop(currentframe); // actually tell the circle which frame we should go to and stop
preloadBar.scaleX = percLoaded;
trace(“onProgress : ” + percLoaded)
}

}

}

Navigate back to the Flash Ide and COMPILE! Select-Control Test Movie.
In Test Movie mode Select-View Simulate Download and you will see the animated preloader in action.
Just to clarify your animation can be as long as you want it to be and as complex as you’d like.
This concludes the article.
Enjoy.

Download sample files.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: