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?
The problem, as I see it, is your calculation of
rgb
. You add the values together which gives you a number between 0 and 3*255 which clearly isn't the value your method expect. You will have to calculate it like thiswhich should be equivalent to this (except for the alpha-value you don't use)
Lastly, as you can see in Chris Haas answer, you can skip this step by converting directly to an int.
Just convert the hex string to an integer:
calcLuminance
only returns a percentage.A little of topic, but here is an extension method to the Color struct I've created to calculate Luminance with different algorithms. Hope it helps you.
The ranges of the
R
,G
andB
from theColor
struct are 0-255.To get the rgb value you expect in your function, you will need to left shift accordingly:
Just use
Color.GetBrightness()
[Edit]
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.