Search code examples
actionscript-3flashactionscriptflash-cs5uiloader

How to add two UILoader inside a UILoader and save the contents of the UILoader using actionscript 3


I have been into a research these past hours in figuring out how to add a UILoader inside a UILoader and save all the contents of a UILoader. I have two instance of UILoader (loader_inner and loader_outer) and they are both placed manually using the UILoader component. The code goes something like this:

loader_inner.load(new URLRequest("background_1.jpg"));
loader_outer.load(new URLRequest("rabbit.jpg"));
loader_outer.addChild(loader_inner);
var bitmapData:BitmapData = new BitmapData(loader_outer.width,loader_outer.height);
bitmapData.draw(loader_outer);
var jpgencoder:JPGEncoder = new JPGEncoder(100);
var mybyte:ByteArray = jpgencoder.encode(bitmapData);
var myfile:FileReference = new FileReference();
myfile.save(mybyte,"test.jpg");

The problem is during save, I can only see the a white image in file but not the two contents. I am expecting a background with a rabbit in the image file that is placed exactly on the two components drawn manually in the work space.


Solution

  • UILoader.load is an asynchronous action. As such, you are attempting to draw the loader to a bitmap before it has actually had a chance to load the images. You will need to listen for COMPLETE events on both inner and outer loaders:

    import com.adobe.images.JPGEncoder;
    import flash.display.Bitmap;
    import flash.events.Event;
    
    loader_inner.addEventListener(Event.COMPLETE, onLoadComplete);
    loader_outer.addEventListener(Event.COMPLETE, onLoadComplete);
    loader_inner.load(new URLRequest("background_1.jpg"));
    loader_outer.load(new URLRequest("rabbit.jpg"));
    loader_outer.addChild(loader_inner);
    
    function onLoadComplete(e:Event):void 
    {
        // check to make sure that *both* loaders have fully loaded
        if(loader_inner.percentLoaded && loader_outer.percentLoaded)
        {
            var bitmapData:BitmapData = new BitmapData(loader_outer.width,loader_outer.height);
            bitmapData.draw(loader_outer);
            var jpgencoder:JPGEncoder = new JPGEncoder(100);
            var mybyte:ByteArray = jpgencoder.encode(bitmapData);
            var myfile:FileReference = new FileReference();
            myfile.save(mybyte,"test.jpg"); 
        }
    }