Using C# I'd like to find out if a Hex color (web format, e.g: #FF2233) is dark or light based on which I can decide what the fore color (font color) should be.
The color is selected by application's users as background of certain elements. The program then needs to figure out if the user's background color is dark then choose white as the font color (for best readability and contrast) otherwise black is chosen.
So far I have been trying to count the number of occurrences of the "F","E","C","D","B" and "A". If there are at least 4 occurrences I consider the color bright. It works for about 70% of times.
Is there a better solution for this?
What if you convert your [Hex color to rgb][1] format then you make the summ of red green and blue if it's over ((255*3)/2) it's a dark color, else it's light color
System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FF2233");
if (col.R * 0.2126 + col.G * 0.7152 + col.B * 0.0722 < 255 / 2)
{
// dark color
}
else
{
// light color
}
Edit: Updated with Luminance, thanks to @Jon idea [1]: How do I get the color from a hexadecimal color code using .NET?
Edit: fixed condition, thanks to @sam360
It's pretty straightforward to compute the luminance of the color from the RGB components. While this will not give the most accurate result on the planet if judged from a human's perspective, it's going to be massively better than other naive attempts.
Given the values of the color components R, G, B, the luminance Y is
Y = 0.2126 R + 0.7152 G + 0.0722 B
You would then pick an arbitrary threshold for Y that separates "dark" from "light" colors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With