1
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – test Dec 8 '14 at 19:58
  • \$\begingroup\$ I don't actually know, I could be wrong. I'm not really familiar with alpha blending. \$\endgroup\$ – LPeter1997 Dec 8 '14 at 20:01
  • 1
    \$\begingroup\$ This gives a pretty good explanation: stackoverflow.com/a/746937/1375538 \$\endgroup\$ – test Dec 8 '14 at 20:08
  • \$\begingroup\$ Pretty sure those ints need to be unsigned. \$\endgroup\$ – ClassicThunder Dec 8 '14 at 20:14
  • \$\begingroup\$ unsigned might be "better", but the >>>24 takes care of it ok, too... \$\endgroup\$ – david van brink Dec 8 '14 at 20:31
1
\$\begingroup\$

What do you mean by "wrong"?

Your first step could be to say clearly (to yourself, or in a unit test, or in this question) "I expected alphaBlend(something,something) to produce (something, preferably a number), but what I got was (something else)." Like, blended red and blue, expected purple, got mauve. Or whatever. Hex values would be clearer...

At a quick reading of the arithmetic, the color output looks correct, although the resulting alpha for a "source over" compositing operation is usually:

a-result = a1 + a2 - a1 * a2

http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.