Search code examples
c#.netcolorshexrgb

How to convert Hex to RGB?


I am trying to use this to figure out if a color is light or dark

Evaluate whether a HEX value is dark or light

Now. It takes in a int

 float calcLuminance(int rgb)
 {
      int r = (rgb & 0xff0000) >> 16;
      int g = (rgb & 0xff00) >> 8;
      int b = (rgb & 0xff);

      return (r*0.299f + g*0.587f + b*0.114f) / 256;
 }

I have a hex color though.

I tried to do this

  var color = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
  int rgb = color.R + color.G + color.B;
   var a = calcLuminance(rgb);

I got 0.11725 I thought it would have to be in the range of 0-256 or something like that.

What am I doing wrong? Do I have to covert R to an int? Or am I just way off?


Solution

  • I am trying to use this to figure out if a color is light or dark

    Just use Color.GetBrightness()


    [Edit]

    I want to determine if I should use white or black for my text. So anything ≤ .5 I should use white and > .5 black?

    There are a number of ways to determine what color to use on a given background, none of which are perfect.

    That last link actually recommends using black/white only, but choosing a cutoff point of 0.73 instead of 0.5. I think you should just go with that, and change it if you find it doesn't work for you.