Search code examples
c#windows-phone-8

How to get System.Windows.Media.Color From From HEX Windows 8 Application


I want to set Border background color from web color value in my windows 8 mobile application .

I found one method that convert hex to Argb but its not working for me ..

  private System.Windows.Media.Color FromHex(string hex)
        {
            string colorcode = hex;
            int argb = Int32.Parse(colorcode.Replace("#", ""), System.Globalization.NumberStyles.HexNumber);
            return System.Windows.Media.Color.FromArgb((byte)((argb & -16777216) >> 0x18),
                                  (byte)((argb & 0xff0000) >> 0x10),
                                  (byte)((argb & 0xff00) >> 8),
                                  (byte)(argb & 0xff));


        }

I am using above method like..

     Border borderCell = new Border();
     var col = FromHex("#DD4AA3");
     var color =new System.Windows.Media.SolidColorBrush(col);
     borderCell.Background = color;

But if I pass color hex value like below

            var col = FromHex("#FFEEDDCC");

its works fine but it not work on my hex color value.

Before posting this question I go thru this stack answer. How to get Color from Hexadecimal color code using .NET?

Convert System.Drawing.Color to RGB and Hex Value


Solution

  • finally I found one method that return color from hex string

     public System.Windows.Media.Color ConvertStringToColor(String hex)
        {
            //remove the # at the front
            hex = hex.Replace("#", "");
    
            byte a = 255;
            byte r = 255;
            byte g = 255;
            byte b = 255;
    
            int start = 0;
    
            //handle ARGB strings (8 characters long)
            if (hex.Length == 8)
            {
                a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
                start = 2;
            }
    
            //convert RGB characters to bytes
            r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
            g = byte.Parse(hex.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber);
            b = byte.Parse(hex.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber);
    
            return System.Windows.Media.Color.FromArgb(a, r, g, b);
        }