Nobien A nerd blog about nerdy things by … nerdy guys?

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;
}
Comments (6) Trackbacks (1)
  1. Just what I needed, thanks!

  2. Thanks!!! Very simple and good

  3. Good stuff mate!
    Really helped me
    thnaks!

  4. 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.

  5. 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;
    }

  6. Legend, this has been giving me a headache all morning.

    It’s people like you that make the internet great!

    Cheers


Leave a comment

(required)