Determine font color based on background color

I encountered similar problem. I had to find a good method of selecting contrastive font color to display text labels on colorscales/heatmaps. It had to be universal method and generated color had to be “good looking”, which means that simple generating complementary color was not good solution – sometimes it generated strange, very intensive colors that were hard to watch and read.

After long hours of testing and trying to solve this problem, I found out that the best solution is to select white font for “dark” colors, and black font for “bright” colors.

Here’s an example of function I am using in C#:

Color ContrastColor(Color color)
{
    int d = 0;
    
    // Counting the perceptive luminance - human eye favors green color...      
    double luminance = (0.299 * color.R + 0.587 * color.G + 0.114 * color.B)/255;
    
    if (luminance > 0.5)
       d = 0; // bright colors - black font
    else
       d = 255; // dark colors - white font
                
    return  Color.FromArgb(d, d, d);
}

This was tested for many various colorscales (rainbow, grayscale, heat, ice, and many others) and is the only “universal” method I found out.

Edit
Changed the formula of counting a to “perceptive luminance” – it really looks better! Already implemented it in my software, looks great.

Edit 2
@WebSeed provided a great working example of this algorithm: http://codepen.io/WebSeed/full/pvgqEq/

Leave a Comment