Search code examples
colorsreadabilitycontrast

How to calculate easy to read color for a random backcolor?


in my current tool there is a colored box with some numbers in it. The backcolor of the box is defined by some sort of list but can also be altered by the user. The forecolor (== fontcolor of the numbers) cannot, and i want to make sure that the user can always read the numbers, so i´d like to adjust the forecolor of the numbers anytime the backcolor changes.

Atm i use code like this:

if(Math.Abs(foreColor.GetBrightness() - backColor.GetBrightness()) <= 0.5f)
{
    if(foreColor.GetBrightness() > 0.5f)
    {
       foreColor = Color.Black;
    }
    else
    {
       foreColor = Color.White;
    }
}

but that is only a workaround for the problem, there are quite a lot of colors (mostly yellows) leading to a bad to read display. Anyone touched a similar problem and found a good solution?


Solution

  • For each color component (assume a range of [0, 255] per component), if it's below 128, saturate it to 255; otherwise make it zero:

    fg.r = bg.r < 128 ? 255 : 0;
    fg.g = bg.g < 128 ? 255 : 0;
    fg.b = bg.b < 128 ? 255 : 0;
    

    This will essentially place the foreground color as far into the octant opposite the background color as possible.