将Color作为#XXXXXX等字符串转换为System.Windows.Media.Brush的最简单方法

时间:2012-02-07 15:20:00

标签: c# colors brush

我认为标题很清楚!

我现在拥有的是:

System.Drawing.Color uiui = System.Drawing.ColorTranslator.FromHtml(myString);
var intColor = (uint)((uiui.A << 24) | (uiui.R << 16) | (uiui.G << 8) | (uiui.B << 0));
var bytes = BitConverter.GetBytes(uint.Parse(value));
var brush = new SolidColorBrush();
brush.Color = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]);

1- myString就像我在标题中所说的那样#FFFFFF

2-这在BitConverter.GetBytes行上失败了,这让我感到惊讶,因为我在我的Color上得到了int表示!

3-无论如何,我知道COlor转换不是那么直观,但我觉得我做得不对...... 这是好方法吗?

3 个答案:

答案 0 :(得分:33)

您可以使用System.Windows.Media.ColorConverter

var color = (Color)ColorConverter.ConvertFromString("#FF010203");
//OR
var color = (Color)ColorConverter.ConvertFromString("#010203");
//OR
var color = (Color)ColorConverter.ConvertFromString("Red");

//and then:
var brush = new SolidColorBrush(color);  

它接受的内容非常灵活。看看examples in XAML here。您可以在。

中传递任何这些字符串格式

注意:这些都在System.Windows.Media(对于WPF),不要与System.Drawing混淆(对于WinForms)

答案 1 :(得分:2)

这是我过去使用的助手类

    public static Color HexStringToColor(string hexColor)
    {
        string hc = ExtractHexDigits(hexColor);
        if (hc.Length != 6)
        {
            // you can choose whether to throw an exception
            //throw new ArgumentException("hexColor is not exactly 6 digits.");
            return Color.Empty;
        }
        string r = hc.Substring(0, 2);
        string g = hc.Substring(2, 2);
        string b = hc.Substring(4, 2);
        Color color = Color.Empty;
        try
        {
            int ri = Int32.Parse(r, NumberStyles.HexNumber);
            int gi = Int32.Parse(g, NumberStyles.HexNumber);
            int bi = Int32.Parse(b, NumberStyles.HexNumber);
            color = Color.FromArgb(ri, gi, bi);
        }
        catch
        {
            // you can choose whether to throw an exception
            //throw new ArgumentException("Conversion failed.");
            return Color.Empty;
        }
        return color;
    }

和一个额外的助手类

        public static string ExtractHexDigits(string input)
        {
            // remove any characters that are not digits (like #)
            var isHexDigit
                = new Regex("[abcdefABCDEF\\d]+", RegexOptions.Compiled);
            string newnum = "";
            foreach (char c in input)
            {
                if (isHexDigit.IsMatch(c.ToString()))
                {
                    newnum += c.ToString();
                }
            }
            return newnum;
        }

答案 2 :(得分:0)

Just use ColorTranslator method:

ColorTranslator.FromHtml("#010203");