如何获取 System.Windows.Media.Color From From HEX Windows 8 应用程序

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

我想在我的 windows 8 移动应用程序中根据 Web 颜色值设置边框背景颜色。

我找到了一种将十六进制转换为 Argb 的方法,但它对我不起作用..

  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));


        }

我正在使用上面的方法,比如..

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

但是如果我像下面这样传递颜色十六进制值

            var col = FromHex("#FFEEDDCC");

它工作正常,但它不适用于我的十六进制颜色值。

在发布这个问题之前,我浏览了这个堆栈答案。 How to get Color from Hexadecimal color code using .NET?

Convert System.Drawing.Color to RGB and Hex Value

最后我找到了一种方法 return 从十六进制字符串

上色
 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);
    }

为什么不直接使用 System.Windows.Media.ColorConverter

Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("#EA1515");