3
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – lightxbulb Feb 2 at 23:24
3
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ 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 $\endgroup$ – Strader Feb 4 at 15:34
  • $\begingroup$ @Strader I don't understand what mean. The difference is a constant 128. $\endgroup$ – user1118321 Feb 5 at 6:47
  • 1
    $\begingroup$ "component = 0x80 ^ component;" should do the trick more succinctly, with a trivial extension to all three components in parallel via 0x808080. $\endgroup$ – Simon F Feb 5 at 11:30
  • $\begingroup$ Found it to be better way to manually lower the alpha of background color for better contrast and calculate inverted one using full alpha $\endgroup$ – Strader Feb 5 at 15:56

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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