Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate whether a HEX value is dark or light

The user of the ASP.NET web app I'm building can select colors for use on some of the elements (e.g. buttons/titles) to facilitate some degree of personalisation.

The problem is that by default the text on those layers is black...what I'm trying to do is to evaluate the HEX value chosen by the user through a picker, and switch between black and white text programmatically - this can be in JavaScript, or in code behind.

The crux of the problem is that I'm just not sure how to evaluate the HEX to make the decision whether the proximity of the chosen color to black is too close to use black text.

Any ideas?

like image 750
Chris Avatar asked Nov 18 '09 07:11

Chris


1 Answers

The methods to do this are built into .Net now:

    var hexcolor = "#FA3CD0";
    var color = System.Drawing.ColorTranslator.FromHtml(hexcolor);
    var brightness = color.GetBrightness();
    if (brightness > .5)
    {
        // color is light
    }
    else
    {
        // color is dark
    }
like image 117
CodeGrue Avatar answered Sep 17 '22 12:09

CodeGrue