Search code examples
colorshex

Intelligent Color Detection


We are working on a medical scheduling system that allows users to define colors to show on the calendar based on a certain status. The issue we have is that if the user picks a dark background color and we are using a dark font, the font doesn't show. Likewise if they pick a light color and we are using a light font. For a variety of reasons, we don't want to have the user setting both colors.

But, we wonder if there is a particular pattern to the hex codes of colors. Perhaps if it is less than a given value, a dark font should be used and a light font used otherwise?

So, is there an intelligent way to programatically pick the font color based on the user's choice of background color?

Amy


Solution

  • You can use the hex codes to mathematically calculate the contrast between two colors. With that information the question is just which color of text (white or black) has more contrast with the chosen background color. This site shows how to write that code in PHP or Javascript, but it could easily be adapted to other languages.

    http://24ways.org/2010/calculating-color-contrast