My friends and family are under attack in Ukraine.
Donate to protect them directly or help international organizations.

Instantiating and displaying MovieClips from loaded SWF

March 7th, 2008

So you want to dynamically load a .swf, instantiate it and add to to a SWFLoader control.

First, loading the .swf:

var loader:Loader = new Loader();
loader.load(url);

Now, to get its classes, we need to listen for the loading completion:

loader.addEventListener(Event.INIT, callbackFunction);

Once done, the callbackFunction will get and instantiate a class:

var mcClass:Class =
loader.content.loaderInfo.applicationDomain
  .getDefinition("className") as Class;
var mc:MovieClip = MovieClip(new mcClass());

Hurray! Now we can add it to some appropriate container:

someSwfLoader.addChild(mc);

Now we want to scale it to fit the available space:

mc.scaleX = mc.scaleY = someSwfLoader.width / mc.width;

(a more complex algorithm may be used)

A problem may arise if your clip content is not at 0,0 coordinates:

var bounds:Rectangle = mc.getBounds(Application.application.stage);
mc.x -= bounds.left * mc.scaleX;
mc.y -= bounds.top * mc.scaleX;

(if you have an ActionScript project instead of Flex, you'll need to access the stage by other means)

Previous: AS3 data binding and component states Next: [Bindable] public override