Convert Hexcodes to Color

Converting a color code string, e.g. "#FFB4DA55" to a Windows.UI.Color proved to be not that simple. Atleast there isn't any buildin way of doing so, so I decided to create a little helper class to do so.

The HelperClass both converts ARBG (colors with alpha values included and RGB colors to Windows.UI.Color.

 

 public class ColorConverterHelper
 {
 public Color HexToColor(String hexString)
 {
 Color outputColor;

 if ((hexString.StartsWith("#")) && (hexString.Length == 9))
 {
 byte a = Byte.Parse(hexString.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
 byte r = Byte.Parse(hexString.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
 byte g = Byte.Parse(hexString.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
 byte b = Byte.Parse(hexString.Substring(7, 2), System.Globalization.NumberStyles.HexNumber);
 outputColor = Color.FromArgb(a, r, g, b);
 }
 else if ((hexString.StartsWith("#")) && (hexString.Length == 7))
 {
 byte r = Byte.Parse(hexString.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
 byte g = Byte.Parse(hexString.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
 byte b = Byte.Parse(hexString.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
 outputColor = Color.FromArgb(255, r, g, b);
 }
 else
 {
 outputColor = Colors.White;
 }

 return outputColor;
 }
 }

I hope the source helps you solving problems like it did for me. Feel free to reach out to me if you have any questions or problems with the implementation.

P.S Make sure you follow me on twitter @deanihansen for more news, design tips, articles and how-to's.