Converting Hexadecimals to Colors in code for Silverlight

Coming from other platforms like HTML, CSS, JavaScript and Flash you will be used to defining colors with hexadecimal values.  Silverlight does support the use of hexadecimal values in XAML, in fact it supports 4 different formats (rgb, argb, rrggbb and aarrggbb). These values are then converted using a special type converter during the parsing of the XAML file.  A string value of #000 is converted into a Color structure that will render black as expected.

Unfortunately this type conversion is not readily accessible when working in code.  In code there are two options built-in, the FromArgb method and system-defined colors.

//using the FromArgb method 
ellipse.Fill = new SolidColorBrush (Color.FromArgb(255, 29, 177, 0));

//using a system-defined color 
ellipse.Fill = new SolidColorBrush (Colors.Green);

As a fan of defining colors using hexadecimals, like myself, you may find switching to bytes in code bothersome. Happily we can do something about this.

The code sample below converts an unsigned integer, which can be written in hexadecimal format, into a Color structure.  Not only are we avoiding string parsing by using the uint type and bitwise operators, we’re also taking advantage of extension methods in C#. This allows us to extend the uint type and reuse this method anywhere in code that has a reference to our ColorExtensions class.

//extensions must be defined in a non-generic static class
public static class ColorExtensions
{
   public static Color ToColor(this uint argb)
   {
      return Color.FromArgb((byte)((argb & -16777216) >> 0x18),
                            (byte)((argb & 0xff0000) >> 0x10),
                            (byte)((argb & 0xff00) >> 8),
                            (byte)(argb & 0xff));
   }
}

//sample usage within a different class
ellipse.Fill = new SolidColorBrush (0xFF1DB100.ToColor());

And that’s it! You can now define color values using hexadecimal in your XAML and C# code.

(If you’re new to Silverlight and want to learn more about the SolidColorBrush class referenced and Brushes in general, check out the Brushes in Silverlight documentation.)

This entry was posted in Client Technologies, Tutorials and tagged , . Bookmark the permalink.

11 Responses to Converting Hexadecimals to Colors in code for Silverlight

  1. Wouldn’t new SolidColorBrush(new Color(0xff, 0x1d, 0xb1, 0x00)) be easier and not force you to put an odd extension method?

  2. curious says:

    why break up the uint into bytes yourself? is there something wrong with the int overload that it doesn’t do that correctly itself?

    http://msdn.microsoft.com/en-us/library/2zys7833.aspx

  3. Adam Kinney says:

    Good point, but unfortunately that overload is not available in Silverlight.

  4. Adam Kinney says:

    Easier as in not needing an extension method yes, but I don’t think its as easy to write out the hex that way. Call it a personal preference thing. Godo to point out an alternative though.

  5. Pingback: Links (1/14/2010) « Steve Pietrek-Everything SharePoint/Silverlight

  6. Pingback: Dew Drop – January 15, 2009 | Alvin Ashcraft's Morning Dew

  7. Jared Potter says:

    A lot of times I get color values from the DOM or an external XML doc and they come back as string. I wrote this a while back and it will convert both hex and color name values.

    public Color StringToColor(string ColorString)
    {
    Color ReturnColor = Colors.Black;

    //Using Hex Code
    if (ColorString[0].ToString() == “#”)
    {
    byte a = 255; //alpha
    byte r = 255; //red
    byte g = 255; //green
    byte b = 255; //blue

    if (ColorString.Length == 9) //8 digit hex (includes the # symbol when counting length)
    {
    a = (byte)(Convert.ToUInt32(ColorString.Substring(1, 2), 16));
    r = (byte)(Convert.ToUInt32(ColorString.Substring(3, 2), 16));
    g = (byte)(Convert.ToUInt32(ColorString.Substring(5, 2), 16));
    b = (byte)(Convert.ToUInt32(ColorString.Substring(7, 2), 16));
    }
    else if (ColorString.Length == 7) //6 digit hex
    {
    r = (byte)(Convert.ToUInt32(ColorString.Substring(1, 2), 16));
    g = (byte)(Convert.ToUInt32(ColorString.Substring(3, 2), 16));
    b = (byte)(Convert.ToUInt32(ColorString.Substring(5, 2), 16));
    }
    else if (ColorString.Length == 4) //3 digit hex
    {
    r = (byte)(Convert.ToUInt32(ColorString.Substring(1, 1) + ColorString.Substring(1, 1), 16));
    g = (byte)(Convert.ToUInt32(ColorString.Substring(2, 1) + ColorString.Substring(2, 1), 16));
    b = (byte)(Convert.ToUInt32(ColorString.Substring(3, 1) + ColorString.Substring(3, 1), 16));
    }
    else if (ColorString.Length == 3) //2 digit hex
    {
    r = (byte)(Convert.ToUInt32(ColorString.Substring(1, 2), 16));
    g = r;
    b = g;
    }

    ReturnColor = Color.FromArgb(a, r, g, b);
    }
    //Using System Colors Colors.Color
    else
    {
    Type colorType = (typeof(System.Windows.Media.Colors));
    if (colorType.GetProperty(ColorString) != null)
    {
    object o = colorType.InvokeMember(ColorString, System.Reflection.BindingFlags.GetProperty, null, null, null);
    if (o != null)
    {
    ReturnColor = (Color)o;
    }

    }
    }

    return ReturnColor;
    }

  8. Pingback: Enlaces Interesantes WPF/Silverlight 16-01-2010 - Blog de Oskar Alvarez

  9. Adam Kinney says:

    That’s nice man, thanks for sharing!

  10. Discorax says:

    Wanted to point out something. If you are building your HEX value from a string you can use these lines to create your color. (took a little Stackoverflow searching to find)

    string hexVal = String.Format(“0xFF{0}{1}{2}”, r, g, b);
    uint hexColor = Convert.ToUInt32(hexVal, 16);
    ColorCollection.Add(hexColor.ToColor());

  11. mohit says:

    Thanks dude it’s working fine for me.

Leave a Reply