BadmintonCat
BadmintonCat

Reputation: 9586

AS3 BitmapData fillRect with Transparency not working as expected

I'm trying to use some fillRects on a 32bit BitmapData (i.e. transparency = true and bg color set to FFFF00FF (opaque magenta). For instance I use:

fillRect(rect, 0xFF0000FF);

This will draw an opaque blue rect, as expected, but ...

fillRect(rect, 0x550000FF);

This should draw a semi-transparent blue rect, right? But instead I'm getting a dark-blue rect as if the blue is mixed with black (but the background is magenta, remember, so I'd expect the blue gets mixed with the underlying magenta?).

If I set the color value to 0x000000FF it should give me the underlying Magenta at 100% but instead I get 100% Black.

The BitmapData is created with a 32bit ARGB so I'm wondering what is wrong here?

Seems this is default AS3 behavior? After creating a small test class it indeed behaves like I explained ...

package 
{
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Sprite;
    import flash.geom.Rectangle;


    public class Main extends Sprite
    {
        public function Main()
        {
            stage.color = 0x000000;
            var bd:BitmapData = new BitmapData(400, 300, true, 0xFFFF00FF);
            var b:Bitmap = new Bitmap(bd);
            addChild(b);

            bd.fillRect(new Rectangle(0, 0, 200, 200), 0x000000FF);
        }
    }
}

You'd expect the rect drawn with fillRect would be Magenta but it obviously takes the bg color of the stage. Now my question is:

Is there a way to get the desired effect (The fillRect alpha applies to the bg color of the bitmapdata, not the Flash stage)?

Upvotes: 0

Views: 4764

Answers (1)

Your problem is in assumption that fillRect is like a tool in photoshop, where you can draw semitransparent rectangle and it will automatically blend.

It is NOT, fillRect just sets all bitmap pixels from specified rectangular region to given colour.

What you have to do is create semi-transparent bitmap with desired size and colour then merge with your working bitmap (canvas) using e.g. draw method, as in this simplified example:

var whiteTransparent:BitmapData = new BitmapData(100, 100, true, 0x80FFffFF);
var blackCanvas:BitmapData = new BitmapData(400, 400, false, 0);

var canvas:Bitmap = new Bitmap(blackCanvas);

addChild(canvas);

blackCanvas.draw(whiteTransparent);

best regards

Upvotes: 2

Related Questions