Question

I want to overlay or more calculate a new color based on two existing.

My colors are stored like this:

int color1 = 0xffFF00FF;
int color2 = 0x00FFFFFF;

Now as you can tell this is assigned in hex format. I know that these will get transformed into "real" numbers at runtime (or during compile).

These hex "strings" are constructed as you know with the first two symbols after the 0x represanting the alpha of this color (e.g. ff and 00 in this case).

I now want to overlay them so I can get the new color int value. I want to be able to choose which algorithm of overlay (screen, multiply, add, subtract, divide, etc.).

I have done LOTS of research on the Internet, but nothing was telling me how to solve my problem.

I've tried a tons of stuff and did intensive testing and debugging, but I am now at a point where I do not now what to do anymore.

For example:

I tried to do some simple math operation to get the add method etc. done like this:

return a + b;
return a - b;
return a * b;
return a / b;
// Even stuff like color burn
return (1 - (1 - a) / b);

I got these from Wikipedia but I guess, based on the output that this is based on on the RGBA format (255/255/255/100) and not the hex stuff.

Then I tried to convert the hex stuff into RGBA values with the java.awt.Color class and binary operations (a && 0xff) and much more.

I am literally working on this for days and I don't know exactly how I have done all these things in detail, but I know none of them worked as expected (e.g. the Alpha value was not taken into account.

Maybe I just have a completely wrong starting point or just were looking and working into the wrong direction. Everything so far (also here on SO) wasn't sufficient for my particular situation. Most of the stuff I' ve found were talking about hex-string to int conversation and opposite ;)

Thanks in advance,

Christian

Was it helpful?

Solution

I guess that you need the weighted average of these values. Something like that:

    int color1 = 0xffFF00FF;
    int color2 = 0x00FFFFFF;

    Color c1 = new Color(color1, true);
    Color c2 = new Color(color2, true);
    int a1 = c1.getAlpha();
    int a2 = c2.getAlpha();

    Color result = new Color((c1.getRed() * a1 + c2.getRed() * a2) / (a1 + a2),
            (c1.getGreen() * a1 + c2.getGreen() * a2) / (a1 + a2),
            (c1.getBlue() * a1 + c2.getBlue() * a2) / (a1 + a2),
            (c1.getAlpha() + c2.getAlpha()) / 2);
    System.out.println(c1);
    System.out.println(c2);
    System.out.println(result);

That should be fine at least for the 3 colors (rgb). I'm not really sure for the alpha...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top