Determining Colour Contrast


I was recently working on one of my home projects that required colour coded drop down list items according to the option they related to. In my project, it was going to be colour coded categories. I wanted to implement colour coding to act as a visual aid for the user interface.

Rather than store the category colour and the foreground colour for the text. I decided that it would be better if I stored a single colour value and let the user interface calculate whether black or white text would be more visible against the colour.

Based on a little research, I came across the W3C Accessibility standards for improving colour visibility for visually impaired web users. This provides a very useful formula for working out the perceived brightness of a colour.

This allowed me to write a very simple, but effective algorithm to perform the simple duty of working out whether the font colour would be best suited as black or white.


public static Color ConstrastColour(Color colour)
    // W3C Accessibility Colour Visibility
    double perBrghtness = ((colour.R * 299) + (colour.G * 587) + (colour.B * 114)) / 1000;
    if (perBrghtness > 120)
       return Color.Black; // bright colors - black font
       return Color.White; // dark colors - white font


Post Categories