Wednesday, April 06, 2005
« Want a VB alternative? Get REAL! | Main | Typing Test Results »

I'm not sure whether I've blogged about this before...gee! I guess I should add some sort of a search/find mechanism to my blog!  I don't think I have, so here goes.

Suppose you're creating some utility that renders graphics or deals with colors and you specifically desire to be able to work with colors in a hex format (e.g. #FF0000) in .NET.  How would you go about taking a hex number and turning it into a System.Drawing.Color?

You might be tempted to look at the Color structure to see if it supports a constructor that accepts such a parameter.  Unfortunately, you'll be hard pressed to find one...maybe if you squint real (and I mean REAL) hard at your monitor it will magically appear.  The Color structure does contain some .FromXXX() methods, but unfortunately none of them take a hex color value.

Following that fruitless foray you might be tempted to parse out the string in chunks of Red, Green, and Blue, convert the strings to their representative integer values and reconstruct a Color via the .FromArgb() method.  Well, that's doable, but it's a lot of work.  Not to mention that #F00 is the same as #FF0000 with respect to html hexadecimal colors, so you need to account for two different hex color formats.

However, after all this, you just can't believe that support for this type of conversion just isn't in the .NET Framework (after all, isn't .NET all about the web anyway? so why wouldn't it be there?), you haven't far to look, you just need to look in the right place.  It turns out that support for this conversion is built-in to the framework.  It's all a part of the System.Drawing.ColorTranslator class.  This handy class allows you to not only convert from a hex number (called an Html color) to a Color, but also your OLE colors, and a Win32 color.

using System.Drawing;
Color foreColor = ColorTranslator.FromHtml(“#FF0033“);

It's exceptionally easy, but it's kinda like the ControlPaint class - easily lost in the myriad of .NET classes.

Wednesday, April 06, 2005 3:23:00 AM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [1]  |  Trackback