Duplicate loaded images in AS3
During the creation of the latest changes in my portfolio site, I needed to duplicate a loaded image that has to be placed as a material in papervison3d's cube. We don't have duplicateMovieClip in AS3, so we have to use another technique.
The answer is to use the Loader object after the loading completes.
package {
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.net.URLRequest;
class ImageLoaderTest {
private
var _loader: Loader;
function ImageLoaderTest(): void {
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoad);
_loader.load(new URLRequest(...));
}
function onImageLoad(e: Event): void {
var duplicatedImage1: MovieClip = getDuplicatedImage();
var duplicatedImage2: MovieClip = getDuplicatedImage();
}
function getDuplicatedImage(): MovieClip {
var m: MovieClip = new MovieClip();
var duplicationBitmap: Bitmap = new Bitmap(Bitmap(_loader.content).bitmapData);
m.addChild(duplicationBitmap);
return m;
}
}
}
To duplicate a Display object you could use the following function:
function duplicateDisplayObject(target: DisplayObject, autoAdd: Boolean = false): DisplayObject {
// create duplicate
var targetClass: Class = Object(target).constructor;
var duplicate: DisplayObject = new targetClass();
// duplicate properties
duplicate.transform = target.transform;
duplicate.filters = target.filters;
duplicate.cacheAsBitmap = target.cacheAsBitmap;
duplicate.opaqueBackground = target.opaqueBackground;
if (target.scale9Grid) {
var rect: Rectangle = target.scale9Grid;
// Flash 9 bug where returned scale9Grid is 20x larger than assigned
rect.x /= 20, rect.y /= 20, rect.width /= 20, rect.height /= 20;
duplicate.scale9Grid = rect;
}
// add to target parent's display list
// if autoAdd was provided as true
if (autoAdd && target.parent) {
target.parent.addChild(duplicate);
}
return duplicate;
}