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.
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.
Sign up to join this communityI 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.
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
color3.r = (color1.r*color2.r)/255
.
\$\endgroup\$
Oct 3, 2014 at 6:15