Skip navigation

Category Archives: ActionScript 3

Maintaining transparency with BitmapData

This took me a while to figure out but it was really simple once I read the docs.

BitmapData.draw example

You want to use the BitmapData class’s draw method to get a “copy” of some thing in ActionScript. You simply create a new BitmapData and then use the draw method and all is well right? Not quite. If you are using the draw method on something that has transparentcy, like a .png image, you might notice that now all of your transparent pixels are white. This is not a bug it is simply because you have not properly set up your BitmapData. If you take a look at the docs BitmapData’s constructor takes a 4th optional parameter called fillColor. The fillColor is a unsigned int that defaults to 0xFFFFFFFF if you do not pass anything in. At first glance you might look at that default value and think hey there are two extra F’s in there, but that is indeed a correct value. The fillColor param is a 32-bit ARGB color value. This mean the first two F’s specify the alpha, then the next two the red, then green, and then blue. This color is used to fill the bitmaps image area and because it is set to 0xFFFFFFFF (solid white) by default you create an all white BitmapData.

Then when you call draw you are drawing on top of the already white BitmapData with the image that has transparency. It is no wonder all the transparent pixels turned white you are really just seeing through the image to the white background. Don’t worry this is very easy to fix just change the default fill color to something transparent like so:

var transBMD:BitmapData = new BitmapData(w, h, true, 0x00ffffff);

You can see here we set the fillColor to 0x00ffffff or white with alpha of 0, this means the BitmapData will have no background color and when we do the draw we will keep our transparency.

Here is a more complete example of the code.

var transBMD:BitmapData = new BitmapData(origImage.content.width * 0.5
    origImage.content.height * 0.5,
    true, 0x00ffffff); //Note the first two 0's mean the alpha level is 0

var trans:Matrix = new Matrix(); //a transform matrix
trans.scale(0.5, 0.5); //scale the image
transBMD.draw(origImage, trans); //draw original image but scale it
var img:Image = new Image();
img.source = new Bitmap(transBMD); //This image will be 50% smaller and still have the transparency

I should also note that if you use BitmapData.copyPixels it will preserve the transparency and is much faster than using draw, but does not allow for stretching, rotating, or adding color effects. If you are not going to be doing any of those copyPixels is a better choice because of it’s speed.

Here is a link to a live Flex example with view source enabled that shows how this all works.
BitmapData.draw example