14May/086
Duplicate a DisplayObject as a BitMap
In working on a project, I created a simple utility class that has this public static method. This basically takes a DisplayObject, copies it, and adds it to a new Sprite which is then returned to the caller. Simple enough. I'm sure this can be refined or done a different way, so have at it.
public static function duplicateImageAsSprite( original:DisplayObject ):Sprite
{
var bitmapData:BitmapData = new BitmapData( original.width , original.height ,
true , 0x000000 );
bitmapData.draw( original as IBitmapDrawable );
var bitmap:Bitmap = new Bitmap( bitmapData );
var returnSprite:Sprite = new Sprite();
returnSprite.addChild( bitmap as DisplayObject );
return returnSprite;
}
October 29th, 2008 - 01:27
Just what I needed, thanks!
August 16th, 2010 - 03:54
Thanks!!! Very simple and good
January 9th, 2011 - 21:32
Good stuff mate!
Really helped me
thnaks!
March 4th, 2011 - 02:49
Thanks for a good idea! I have to add though, that it’s better clone the transform property of a display object too, so that its bitmap clone possesed all the transformation applied to it.
March 4th, 2011 - 03:58
Here’s what I came up with, based on your approach. This function duplicates displayObject no matter of where his registration point is (so that it doesn’t clip).
public static function duplicateAsBitmap(displayObj:DisplayObject):Sprite{
if(displayObj.width > 2880 || displayObj.height > 2880){
throw new Error(“The size of display object exceeds 2880 px and cannot be rendered as bitmap”);
return;
}
else{
var btmpData:BitmapData = new BitmapData(displayObj.width, displayObj.height, true, 0xffffff);
var btmp:Bitmap = new Bitmap();
var m:Matrix = new Matrix();
var bounds:Rectangle = displayObj.getBounds(displayObj);
var sprite:Sprite = new Sprite();
m.translate(-bounds.x, -bounds.y);
btmpData.draw(displayObj, m);
btmp.bitmapData = btmpData;
btmp.smoothing = true;
btmp.transform = displayObj.transform;
btmp.x += bounds.x;
btmp.y += bounds.y;
sprite.addChild(btmp);
}
return sprite;
}
March 16th, 2011 - 08:46
Legend, this has been giving me a headache all morning.
It’s people like you that make the internet great!
Cheers