Instantiating and displaying MovieClips from loaded SWF
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)
Thanks so much for this. This approach is going to help me develop an API I’m working on. I needed this approach to keep the design and the API code separated and still be able to load all of the creative team’s assets without them having to worry about code dependencies.
Thanks!
Thanks very much–one detail–I think the “instanceName” should be a “className” (since it’s the name of the class itself, not a specific instance of that class)
You are correct. “className” makes more sense. I edited the post.