Silverlight 2.0 is missing a ColorConverter. There’s no easy and efficient way from code to convert from a HEX color format to a built in Color type. I like being able to paste standard web color formats into my source code without converting them to a Color.FromArgb byte format (as most web color selectors support that format).

I wrote this code to end this annoyance (but didn’t bother with a full-fledged TypeConverter):

public static class Extensions
{
    public static void SetFromHex ( this Color c, string hex )
    {
        Color c1 = ToColorFromHex(hex);

        c.A = c1.A;
        c.R = c1.R;
        c.G = c1.G;
        c.B = c1.B;                        
    }
public static Color ToColorFromHex ( string hex )
{
    if(string.IsNullOrEmpty(hex))
    {
        throw new ArgumentNullException("hex");
    }

    // remove any "#" characters
    while(hex.StartsWith("#"))
    {
        hex = hex.Substring(1);
    }

    int num = 0;
    // get the number out of the string 
    if(!Int32.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out num))
    {
        throw new ArgumentException("Color not in a recognized Hex format.");
    }

    int[] pieces = new int[4];
    if(hex.Length > 7)
    {
        pieces[0] = ((num >> 24) & 0x000000ff);
        pieces[1] = ((num >> 16) & 0x000000ff);
        pieces[2] = ((num >> 8) & 0x000000ff);
        pieces[3] = (num & 0x000000ff);
    }
    else if(hex.Length > 5)
    {
        pieces[0] = 255;
        pieces[1] = ((num >> 16) & 0x000000ff);
        pieces[2] = ((num >> 8) & 0x000000ff);
        pieces[3] = (num & 0x000000ff);
    }
    else if(hex.Length == 3)
    {
        pieces[0] = 255;
        pieces[1] = ((num >> 8) & 0x0000000f);
        pieces[1] += pieces[1] * 16;
        pieces[2] = ((num >> 4) & 0x000000f);
        pieces[2] += pieces[2] * 16;
        pieces[3] = (num & 0x000000f);
        pieces[3] += pieces[3] * 16;
    }
    return Color.FromArgb((byte) pieces[0], (byte) pieces[1], (byte) pieces[2], (byte) pieces[3]);
}

}

 

It accepts 3 standard formats for colors:

  1. [ALPHA][RED][GREEN][BLUE] (alpha and all colors)
  2. [RED][GREEN][BLUE] (no alpha channel, automatically set to 255)
  3. Short hand [R][G][B] (takes the single digit hex number and adds it to the same number * 16, alpha set to 255);

To use the function:

Color c1 = Extensions.ToColorFromHex("#00B2D6E8");

Obviously the built in components, brushes, etc. support that format already, but there doesn’t seem to be any place that functionality is exposed.

Related Content

Subscribe to the post comments feeds or Leave a trackback