Tatham Oddie

Contrasting Colours in C#

leave a comment »

It’s still not perfect … but this is a bit of code another developer and I came up with a while ago for finding contrasting colours.


/// <summary>
/// From a given colour it works out a suitable colour that will sit on top of
/// it so that the contrast is suitable for readability.
/// </summary>
/// <param name="baseColor">Color to get the contrasting complement of</param>
/// <returns>Contrasting color</returns>
public static Color GetContrastingColor(Color baseColor)
{
    HSB baseHsb = ColorToHsb(baseColor);
    int newSaturation = baseHsb.Saturation;
    int newBrightness = baseHsb.Brightness;

    if ((baseHsb.Saturation >= 40 && baseHsb.Saturation <= 60) && (baseHsb.Brightness >= 40 && baseHsb.Brightness <= 60))
    {
        newSaturation = (baseHsb.Saturation <= 50 ? 100 : 0);
        newBrightness = (baseHsb.Brightness <= 50 ? 100 : 0);
    }
    else if (baseHsb.Saturation >= 40 && baseHsb.Saturation <= 60)
    {
        newSaturation = (baseHsb.Saturation <= 50 ? 100 : 0);
    }
    else if (baseHsb.Brightness >= 40 && baseHsb.Brightness <= 60)
    {
        newBrightness = (baseHsb.Brightness <= 50 ? 100 : 0);
    }
    else
    {
        newSaturation = 100 - baseHsb.Saturation;
        newBrightness = 100 - baseHsb.Brightness;
    }

    if (baseHsb.Saturation == 0)
    {
        newSaturation = 0;
    }

    HSB newHsb = new HSB(baseHsb.Hue, newSaturation, newBrightness);
    return HsbToColor(newHsb);
}


Written by Tatham Oddie

April 1, 2006 at 23:34

Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.