Simpliest way to convert a Color as a string like #XXXXXX to System.Windows.Media.Brush

前端 未结 3 797
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 12:55

I think that the title is clear !

What I have now is :

System.Drawing.Color uiui = System.Drawing.ColorTranslator.FromHtml(myString);
var intColor =          


        
相关标签:
3条回答
  • 2021-01-17 12:58

    You can use the 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);  
    

    It's pretty flexible as to what it accepts. Have a look at the examples in XAML here. You can pass any of those string formats in.

    Note: These are all in System.Windows.Media (for WPF) not to be confused with System.Drawing (for WinForms)

    0 讨论(0)
  • 2021-01-17 12:58

    This is the helper class that I've used in the past

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

    and an additional helper class

            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;
            }
    
    0 讨论(0)
  • 2021-01-17 13:23

    Just use ColorTranslator method:

    ColorTranslator.FromHtml("#010203");
    
    0 讨论(0)
提交回复
热议问题