System.Drawing.ColorConvertor class

Found this cool little class while reading up on the System.Drawing namespace, an area of .NET I’ve had little experience of. There seems to be scant information around so maybe this will help someone.

The ColorConvertor class can be used to convert string representations of a colour (or “color” if you live in the US) to an instance of the Color class. It’s very simple to use:

ColorConverter conv = new ColorConverter();
Color blueCol = (Color)conv.ConvertFromString("blue");

This will give you an instance of Color set to blue.

Well that’s pretty cool if you want to pass a string to an instance of the Color object without having to write your own parsing method. Probably more useful is this:

ColorConverter cc = new ColorConverter();
Color c = (Color)cc.ConvertFromString("#ff0000");

This gives you a Color object set to red. Being able to parse a hex representation of an RGB colour could be very useful, this class makes it easy!

You can also pass back to a string too:

string strCol = cc.ConvertToString(blueCol);

Leave a Reply