Invert a Color in C#
A very quick code snippet for you all today. I had encountered an issue where I needed to invert the text color from the background (color was changing consistently from the user). So after some googling and playing around, I created something to do just that for me.
First we needed a method to take convert our color to a hex string :
//Modified from http://snipplr.com/view/13358/
private static Color HexToColor(string hexColor)
{
//Remove # if present
if (hexColor.IndexOf('#') != -1)
hexColor = hexColor.Replace("#", "");
byte red = 0;
byte green = 0;
byte blue = 0;
if (hexColor.Length == 8)
{
//We need to remove the preceding FF
hexColor = hexColor.Substring(2);
}
if (hexColor.Length == 6)
{
//#RRGGBB
red = byte.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier);
green = byte.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier);
blue = byte.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier);
}
else if (hexColor.Length == 3)
{
//#RGB
red = byte.Parse(hexColor[0].ToString() + hexColor[0].ToString(), NumberStyles.AllowHexSpecifier);
green = byte.Parse(hexColor[1].ToString() + hexColor[1].ToString(), NumberStyles.AllowHexSpecifier);
blue = byte.Parse(hexColor[2].ToString() + hexColor[2].ToString(), NumberStyles.AllowHexSpecifier);
}
return Color.FromRgb(red, green, blue);
}
Then we can do the inversion :
private Brush invertColor(string value)
{
if (value != null)
{
Color ColorToConvert = HexToColor(value);
Color invertedColor = Color.FromRgb((byte)~ColorToConvert.R, (byte)~ColorToConvert.G, (byte)~ColorToConvert.B);
return new SolidColorBrush(invertedColor);
}
else
{
return new SolidColorBrush(Color.FromRgb(0,0,0));
}
}
Finally for the example of use, we can just set the foreground from the background (or whatever you need done)
//TestLabel is just a label on the wpf form //mainGrid is the main grid on the wpf form TestLabel.Foreground = invertColor(mainGrid.Background.ToString());
There you go, an inverted color. Happy coding and HTH!