# Getting contrast color to a given color in RGB or ARGB or HEX

I am looking for a stable way to find a contrast/inverted/opposite color to a given one.

Application of this is to find best possible color for foreground to give background.

• You could try the complementary colors. So if you have $c \in [0,1]^3$ then $(1,1,1) - c$. You can use luma to control luminance. – lightxbulb Feb 2 at 23:24

I read this in a magazine article probably 25 years ago. I don't recall the full derivation, but they said to take each component (red, green, and blue) and invert the high bit of the color. In a C-like programming language, you could do:

 component = (~component & 0x80) | (component & 0x7F);


This can be simplified to:

component ^= 0x80;


for a single component or to:

component ^= 0x80808000;


if you want to do 4 components at once (and don't affect the alpha).

This assumes your components are 8-bit values. This avoids the problems you get with the middle values if you simply invert them. In that case 127 becomes 128, and vice-versa. But with the above solution, 127 becomes 255 and 128 becomes 0.

• This is a great way, but as i get closer to 127 in R or G or B values, lower is the difference between colors – Strader Feb 4 at 15:34
• @Strader I don't understand what mean. The difference is a constant 128. – user1118321 Feb 5 at 6:47
• "component = 0x80 ^ component;" should do the trick more succinctly, with a trivial extension to all three components in parallel via 0x808080. – Simon F Feb 5 at 11:30
• Found it to be better way to manually lower the alpha of background color for better contrast and calculate inverted one using full alpha – Strader Feb 5 at 15:56