Get BitmapData from a displayObject included transparent area, and effect area

Ratha Hin picture Ratha Hin · Aug 5, 2011 · Viewed 8.5k times · Source

I have this function:

    public static function cloneDpObj(target:DisplayObject):Bitmap
    {
        var duplicate:Bitmap;

        var tBitData:BitmapData = new BitmapData(target.width, target.height);
        tBitData.draw(target);
        duplicate = new Bitmap(tBitData);

        return duplicate;
    }

to clone target displayObject (MovieClip or Sprite) and return Bitmap Object.

It can get bitmap from the target object, but it seem don't get all the area of the image.

By give the width and height of target object, but the target object in design was applied by Glow Effect, so my question can we get the all view of bitmapdata from a displayobject?

Answer

Michael Antipin picture Michael Antipin · Aug 5, 2011

BitmapData.draw() takes a snapshot of a given object removing all transformations and filters applied on the stage. Resulting image shows object as it is present in your movie library.

There are two basic options when drawing display objects with transformations and/or filters.

  1. You can apply all transformations during drawing with matrix parameter for BitmapData.draw(). After drawing you can apply filters to resulting bitmap with BitmapData.applyFilter().
  2. Just draw parent container, not the object itself.

I usually choose the latter. That's pretty straightforward. There are some disadvantages: if you choose the second method, your target has to have a display list parent and you may draw unwanted content that resides in parent container. (However, these drawbacks are easily eliminated.)

// bounds and size of parent in its own coordinate space
var rect:Rectangle = target.parent.getBounds(target.parent);
var bmp:BitmapData = new BitmapData(rect.width, rect.height, true, 0);

// offset for drawing
var matrix:Matrix = new Matrix();
matrix.translate(-rect.x, -rect.y);

// Note: we are drawing parent object, not target itself: 
// this allows to save all transformations and filters of target
bmp.draw(target.parent, matrix);