Display correct text colour on a background colour
Hi,
I haven’t posted for a bit, back to some handy C++. I’ve been working with a lot of text being displayed on a background which can be various colours. Not knowing the background colour is in advance is problematic as if you specify the text colour to be always white and the background colour changes to white then the text is unreadable. Likewise for black and there are a range of colours in between that suffer with the same problem, light grey or dark purple for example.
I needed a way of determining correct text colour based on a given background colour. After doing a little bit of digging I came across this article on CodeProject which almost gives the solution I was looking for. However I want to just display white or black text depending on the background colour. So here is the code I used to do so, it works remarkably well. I’ve pseudo coded it up a bit to remove various bits and pieces that may not be important but you can just replace bits of it with proper objects. Also ignore the magic numbers, they’re there just to show the numbers that worked for me. This algorithm can potentially be used in any language, I’m using C++ here as it is what I’m currently using.
COLOUR GetTextColourFromBackground(COLOUR BackgroundColour)
{
uint32 uDarkLightColourThreshold(105);
float fRedThresholdValue(0.299);
float fGreenThresholdValue(0.587);
float fBlueThresholdValue(0.114);
uint8 bgDelta = static_cast((BackgroundColour.GetRed() * fRedThresholdValue) + (BackgroundColour.GetGreen() * fGreenThresholdValue) +
(BackgroundColour.GetBlue() * fBlueThresholdValue));
COLOUR TextColour(GetColour(White));
if((255 - bgDelta) < uDarkLightColourThreshold)
{
TextColour = GetColour(Black);
}
return TextColour;
}
So on a white background the text colour returned will be black and on a black background the text colour will be white. Also on a light grey background the colour returned will be black and so on.
The formula used above originally comes from the W3C http://www.w3.org/TR/AERT#color-contrast.