.NET Get Contrasting Text Color

@DrDanyo, this is for you!

In my Pluralsight course, Hacking the User Experience - UX for Developers, I talk about using code to get around the problem of picking the right text color.

Here is a small .NET static method that will calculate a contrasting text color (black or white) for any background color that you pass in.

This code uses the YIQ color model and is based on the great JavaScript example by Brian Suda.

using System;
using System.Linq;
using System.Windows.Media;

namespace YIQTextColor
{
    public static class ColorHelper
    {
        public static Color GetContrastingTextColor(Color background)
        {
            var r = background.R;
            var g = background.G;
            var b = background.B;

            var yiq = ((r*299)+(g*587)+(b*114))/1000;

            return (yiq >= 128) ? Colors.Black : Colors.White;
        }
    }
}

I hope this code helps you!

BONUS DLC!

If you are a WPF developer, you can wrap this static method with a custom value converter and automatically pick colors right from your XAML.

Here is my value converter:

using System;
using System.Linq;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;

namespace YIQTextColor
{
    public class BackgroundColorToTextColorConverter : MarkupExtension, IValueConverter
    {
        private static BackgroundColorToTextColorConverter converter = null;

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (converter == null)
            {
                converter = new BackgroundColorToTextColorConverter();
            }

            return converter;
        }

        public object Convert(object value, System.Type targetType, 
            object parameter, System.Globalization.CultureInfo culture)
        {
            var background = (Color)ColorConverter.ConvertFromString(value.ToString());

            return new SolidColorBrush(ColorHelper.GetContrastingTextColor(background));
        }

        public object ConvertBack(object value, System.Type targetType, 
            object parameter, System.Globalization.CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }
}

Here is a sample piece of XAML to show you how it works:

<Border x:Name="Border1" Background="Orange" Height="50" Width="200" Margin="5">
    <TextBlock Text="Hello world!" 
        Foreground="{Binding ElementName=Border1, Path=Background, 
            Converter={local:BackgroundColorToTextColorConverter}}" 
        VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Border>

Share this post:

by Keith Harvey

Technical Architect, Developer, UX Visionary, and Pluralsight Author with a focus on Microsoft technologies.

https://twitter.com/keithernet