Convert Hexadecimal String to System.Windows.Media.Color

Posted: November 17, 2011 in Windows Phone 7 & Mango

To convert a hex string to ARGB colour, you can try the following:

private Color ConvertHexStringToColour(string hexString)
{
  byte a = 0;
  byte r = 0;
  byte g = 0;
  byte b = 0;
  if (hexString.StartsWith("#"))
  {
    hexString = hexString.Substring(1, 8);
  }
  a = Convert.ToByte(Int32.Parse(hexString.Substring(0, 2), 
      System.Globalization.NumberStyles.AllowHexSpecifier));
  r = Convert.ToByte(Int32.Parse(hexString.Substring(2, 2), 
      System.Globalization.NumberStyles.AllowHexSpecifier));
  g = Convert.ToByte(Int32.Parse(hexString.Substring(4, 2), 
      System.Globalization.NumberStyles.AllowHexSpecifier));
  b = Convert.ToByte(Int32.Parse(hexString.Substring(6, 2), System.Globalization.NumberStyles.AllowHexSpecifier));
  return Color.FromArgb(a, r, g, b);
}

To use the above, you can do the following:

String strColour = "#FFFFFFFF";
Color myColour = ConvertHexStringToColour(strColour);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s