Thursday, May 24, 2012

Convert Hexa string to Color in Silverlight

Below method will convert Color from Hexa string.

 public static Color GetColorFromHexa(string hexaColor)
 {
    if (string.IsNullOrEmpty(hexaColor))
                return Colors.Transparent;
    if (hexaColor.Length == 9)
    {
       return Color.FromArgb(
        Convert.ToByte(hexaColor.Substring(1, 2), 16),
        Convert.ToByte(hexaColor.Substring(3, 2), 16),
        Convert.ToByte(hexaColor.Substring(5, 2), 16),
        Convert.ToByte(hexaColor.Substring(7, 2), 16));
    }
    else if (hexaColor.Length == 7)
    {
        return Color.FromArgb(
         Convert.ToByte("FF", 16),
         Convert.ToByte(hexaColor.Substring(1, 2), 16),
         Convert.ToByte(hexaColor.Substring(3, 2), 16),
         Convert.ToByte(hexaColor.Substring(5, 2), 16)
        );
    }
    else
    {
        return Colors.Transparent;
    }

 }

I have created method that convert hexa string to SolidColor.Color value.

If i am passing Hexa string to 7 cahracter then it will add  first two character for opacity.

so above method will return SolidColor.Color value from Hexa string

No comments:

Post a Comment