This should be a simple question, but I haven\'t been able to find a way to make it work.
Essentially, I have a silly localhost page that I use in my webdevelopment.
private Color GetContrastingColor(Color color)
{
int r = color.R > 0 ? 256 - color.R : 255;
int g = color.G > 0 ? 256 - color.G : 255;
int b = color.B > 0 ? 256 - color.B : 255;
return System.Drawing.Color.FromArgb(r, g, b);
}
Thanks to @starblue !
Here is C#
code that I use
public static string GetContrastBlackOrWhiteColorAsHtmlColorCode(Color c)
{
System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml("transparent");
try
{
if (c.R >= 128 && c.G >= 128 && c.B >= 128)
{
return System.Drawing.ColorTranslator.ToHtml(Color.Black);
}
else
{
return System.Drawing.ColorTranslator.ToHtml(Color.White);
}
}
catch (Exception)
{
}
return System.Drawing.ColorTranslator.ToHtml(color);
}
You can use method GetBrightness()
on Color
class. It returns a float value from 0.0 (brightness of black) to 1.0 (white).
A simple solution would be:
var color1 = new Color.FromArgb(r1, g1, b1);
var brightness = color1.GetBrightness();
var color2 = brightness > 0.5 ? Color.Black : Color.White;
Check out this PHP solution: Calculating Color Contrast with PHP by Andreas Gohr. It can be ported to any language of course.
He also has a very nice demonstration of his contrast analyzer where you can find some minimal contrast levels to work with.
If you flip all the bits, you will get the "opposite" color which would be pretty good contrast.
I believe it's the ~ operator in C#:
R2 = ~R1;
G2 = ~G1;
B2 = ~B1;
These answers are more or less suggesting to use one of the two or three color choices based on whether the color is bright or dark.
I use a bit different approach and it worked elegantly in my case. Here is the implementation.
int color = your_color;
contrastColor = Color.rgb(255-(color >> 16)&0xFF, 255-(color >> 8)&0xFF, 255- color&0xFF);
It's simple and wonderful.