Using System.Drawing.Color
Wednesday, November 11, 2009 7:08:00 AM
The System.Drawing namespace within .NET contains a slew of powerful features. I won’t go into the capabilities that exist, but encourage you to check it out. This specific post of all about Colors. There are many times when I have wanted to translate and use colors within ASP.NET. In that, I have wanted to “transform” from the Color object to a named color to a Hex value and everything in between. I thought I would provide a quick example that loads a dropdown list with all the Colors. In going through the colors, each iteration will get the color name, create a color object from the color name, create a hex value from the color using a known color and create a color from the hex value. There are a few different ways to do almost all of these and I will show a few where I can. The code below is commented to show where things occur and is intended to be the "tutorial".
//Get our colors as a String array
String[] myColorNames = Enum.GetNames(typeof(System.Drawing.KnownColor));
//Loop through the color names and “do stuff”
for (Int32 x = 0; x < myColorNames.Length; x++)
{
//Get the string name of our color
String myColorName = myColorNames[x];
//Get our KnownColor
System.Drawing.KnownColor myColorKnown = (System.Drawing.KnownColor)System.Enum.Parse(typeof(System.Drawing.KnownColor), myColorName);
//Get our color object back from the string name
System.Drawing.Color myColor = System.Drawing.Color.FromKnownColor(myColorKnown);
/*Get the hex value of our color. We could use Drawing.ColorTranslator.
However, there is a problem with ColorTranslator, where if you are using a control that allows selection of the system
colors (Control, ControlDark, etc.), it will still return a name.*/
String myColorHex = String.Format( "#{0:x2}{1:x2}{2:x2}", myColor.R, myColor.G, myColor.B);
//We can also get our Hex value this way:
myColorHex = "#" + System.Drawing.Color.FromKnownColor(myColorKnown).ToArgb().ToString("X").Remove(0, 2);
//Turn our hex back into a Color
myColor = System.Drawing.Color.FromArgb(Int32.Parse(myColorHex.Replace("#", ""), System.Globalization.NumberStyles.HexNumber));
//Another way to turn our hex into a color
myColor = System.Drawing.ColorTranslator.FromHtml(myColorHex);
//Add our item to the Dropdown list and change the background color to our color
ListItem myItem = new ListItem(myColorName + " = " + myColorHex, myColorName);
myItem.Attributes.Add("style", "font-weight: bold; background-color: " + myColorHex);
ddlColors.Items.Add(myItem);
}
Happy Coloring!