# Alpha blending sometimes gives the wrong color?

I've got a method for alpha blending:

public static int alphaBlend(int c1, int c2) {
int a1 = (c1 & 0xff000000) >>> 24;

int r1 = (c1 & 0x00ff0000) >> 16;
int r2 = (c2 & 0x00ff0000) >> 16;

int g1 = (c1 & 0x0000ff00) >> 8;
int g2 = (c2 & 0x0000ff00) >> 8;

int b1 = (c1 & 0x000000ff);
int b2 = (c2 & 0x000000ff);

float src_alpha = ((float)a1) / 255.0f;

int red   = (int) ((r1 * src_alpha) + (r2 * (1.0f - src_alpha)));
int green = (int) ((g1 * src_alpha) + (g2 * (1.0f - src_alpha)));
int blue  = (int) ((b1 * src_alpha) + (b2 * (1.0f - src_alpha)));

return (a1 << 24) | (red << 16) | (green << 8) | blue;
}


But sometimes this gives the wrong color (I guess because I don't use the second color's alpha). Could anyone explain how to fix this?

• I could be reading this wrong but are you sure you should be putting a1 back into the result? You don't actually do anything to that value.
– test
Dec 8, 2014 at 19:58
• I don't actually know, I could be wrong. I'm not really familiar with alpha blending. Dec 8, 2014 at 20:01
• This gives a pretty good explanation: stackoverflow.com/a/746937/1375538
– test
Dec 8, 2014 at 20:08
• Pretty sure those ints need to be unsigned. Dec 8, 2014 at 20:14
• unsigned might be "better", but the >>>24 takes care of it ok, too... Dec 8, 2014 at 20:31