Useful Code Snippet: Contrasting Color
February 16th, 2008
When working on an application I wanted that the drawn text is always well readable on the background. The background color can be changed by the user. In order not have same or similar colors for background and foreground I directly thought of contrasting colors.
I just binded background color and value of the font color to each other. In other words the foreground color is set when changing the background in dependency to the value of background color.
I didn’t want to withhold you the function I used, it’s a nice reusable snippet of code:
#define TOLERANCE 0x40 int GetContrastColor (int cBg) { if ( abs(((cBg ) & 0xFF) - 0x80) <= TOLERANCE && abs(((cBg >> 8) & 0xFF) - 0x80) <= TOLERANCE && abs(((cBg >> 16) & 0xFF) - 0x80) <= TOLERANCE ) return (0x7F7F7F + cBg) & 0xFFFFFF; else return cBg ^ 0xFFFFFF; }
It takes an integer for the background color that has 0xRRGGBB or 0xBBGGRR format.
The color is made up of three parts (red, green, blue), each part is tested if it’s close to 0×80 (128 in decimal). If all three match 0x7F7F7F is added to the color to get the best possible different color.
For the comparison with the TOLERANCE absolut value the function abs is needed.
abs(x) takes and integer or long value and returns the absolute value of parameter it is given.
If the given value is complex, it returns the complex modulus (magnitude), which is the same as
sqrt(real(X).^2 + imag(X).^2)
It’s definied in math.h, but to verify that the function also works without math header you can add this ifndef-block:
#ifndef abs #define abs(x) ((x) < 0 ? (-(x)) : (x)) #endif
Finally it’s important to prevent an overflow (range only goes from 0x000000 to 0xFFFFFF). The result simply is ANDed with 0xFFFFFF.





