Based on the information on this blog entry, I could come up with the following C# code, that returns either Color.Black
or Color.White
for the best contrast with the given (background) color:
public Color GetContrastingColor(Color backColor)
{
int r = (int)backColor.R;
int g = (int)backColor.G;
int b = (int)backColor.B;
int yiqSpace = ((r * 299) + (g * 587) + (b * 114)) / 1000;
if (yiqSpace > 131)
{
return Color.Black;
}
else
{
return Color.White;
}
}
The method uses YIQ to determine if a color is considered light or dark, and returns a constrasting color in return.