calculating transparency

Hello there!

Sorry, I’m from Austria and my english isn’t the best… but I have a drawing Problem in my 2D-Game.

I load the Images and store them in an Array by using the PixelGrabber class. But now I have a problem by drawing Images one upon the other.

For Example, I have these Values:

-65280 1357369291
-65280 518382559
-65280 114414291

Left ist the Background (red), right the foreground of an *.png Image with Alpha.

How to combine, calculate back- and foreground?

Hi BillieJoe,
You have to split the values into their integer colour channels. Off the tope of my head:


// bgcol = BackGround Colour
// fgcol = Foreground Colour

int blend( int bgcol, int fgcol )
{
    int bg_r = bgcol&0xff;
    int bg_g = bgcol&0xff00;
    int bg_b = bgcol&0xff0000;

    int fg_r = fgcol&0xff;
    int fg_g = fgcol&0xff00;
    int fg_b = fgcol&0xff0000;

    int alpha = fgcol >> 24;

Alpha blending operation is as follows:

Final = (FG - BG) * Alpha + BG;

When alpha = 0, Final = BG, when alpha = 1, Final = FG.
In code:


    // Blend values
    bg_r += ( (fg_r - bg_r) * alpha)>>8;
    bg_g += ( (fg_g - bg_g) * alpha)>>8;
    bg_b += ( (fg_b - bg_b) * alpha)>>8;
    // Mask channels back to 8 bit
    bg_r &= 0xff;
    bg_g &= 0xff00;
    bg_b &= 0xff0000;
    // Return combined RGB values, with 255 as the alpha
    return ( 0xff000000 + bg_r + bg_g + bg_b);
}

This can be optimised as you can do the B and R parts simultaneously. Hope this helps,

  • Dom

Thanks a lot, it works!