4
$\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$
1
  • $\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
    Commented Feb 2, 2019 at 23:24

1 Answer 1

4
$\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$
4
  • 1
    $\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
    Commented Feb 4, 2019 at 15:34
  • $\begingroup$ @Strader I don't understand what mean. The difference is a constant 128. $\endgroup$ Commented Feb 5, 2019 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
    Commented Feb 5, 2019 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
    Commented Feb 5, 2019 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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