3
\$\begingroup\$

I have two RGBA integers. What procedure should I perform on them to return the multiplied colour? Do I need to split the RGBA integer into its component integers (R, G, B, A)?

I'm using this for a lighting engine.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Just thinking about it for a second, could you just take the average of both R's, both Gs, and both Bs, and create a new colour using those averages? I could, however, be completely wrong and that creates an entirely different colour, but you might as well try it. \$\endgroup\$
    – drdavehere
    Oct 2, 2014 at 18:39
  • \$\begingroup\$ convert them to floats (0-1) and then multiply \$\endgroup\$
    – CobaltHex
    Oct 2, 2014 at 19:47

1 Answer 1

4
\$\begingroup\$

Convert them to the normalised space:

float r1 = color1.r / 255.0f;
float g1 = color1.g / 255.0f;
float b1 = color1.b / 255.0f;
float a1 = color1.a / 255.0f;

float r2 = color2.r / 255.0f;
float g2 = color2.g / 255.0f;
float b2 = color2.b / 255.0f;
float a2 = color2.a / 255.0f;

and them multiply them:

float r3 = r1 * r2;
float g3 = g1 * g2;
float b3 = b1 * b2;
float a3 = a1 * a2;

to convert back to the 0-255 range:

Color color3 = new Color();
color3.r = r3 * 255;
color3.g = g3 * 255;
color3.b = b3 * 255;
color3.a = a3 * 255;

this is the correct procedure to multiply two colors.

EDIT: Thanks for Petr Abdulin for pointing out: You can use some math here and simplify the calculation:

color3.r = (color1.r * color2.r) / 255;
color3.g = (color1.g * color2.g) / 255;
color3.b = (color1.b * color2.b) / 255;
color3.a = (color1.a * color2.a) / 255;

Explanation:

c3 = ((c1 / 255) * (c2 / 255)) * 255; //multiply fractions
c3 = ((c1 * c2) / (255 * 255)) * 255; //multiply fraction with whole number
c3 = (c1 * c2 * 255) / (255 * 255)); //cancel 255 on top of fraction with 255 on bottom of fraction
c3 = (c1 * c2) / 255; //final result
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Simple optimization gives just: color3.r = (color1.r*color2.r)/255. \$\endgroup\$ Oct 3, 2014 at 6:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .