简体   繁体   English

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

[英]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 . 我想在我的Windows 8移动应用程序中从Web颜色值设置边框背景颜色

I found one method that convert hex to Argb but its not working for me .. 我找到了一种方法将十六进制转换为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));


        }

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? 如何使用.NET从十六进制颜色代码中获取颜色?

Convert System.Drawing.Color to RGB and Hex Value 将System.Drawing.Color转换为RGB和Hex值

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

Why not simply use System.Windows.Media.ColorConverter? 为什么不简单地使用System.Windows.Media.ColorConverter?

Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("#EA1515"); 颜色=(颜色)System.Windows.Media.ColorConverter.ConvertFromString(“#EA1515”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM