【问题标题】:Creating SolidColorBrush from hex color value从十六进制颜色值创建 SolidColorBrush
【发布时间】:2012-04-08 11:16:49
【问题描述】:

我想从 #ffaacc 等十六进制值创建 SolidColorBrush。我该怎么做?

在 MSDN 上,我得到了:

SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 0, 0, 255);

所以我写了(考虑到我的方法接收颜色为#ffaacc):

Color.FromRgb(
  Convert.ToInt32(color.Substring(1, 2), 16), 
  Convert.ToInt32(color.Substring(3, 2), 16), 
  Convert.ToInt32(color.Substring(5, 2), 16));

但这给出了错误

The best overloaded method match for 'System.Windows.Media.Color.FromRgb(byte, byte, byte)' has some invalid arguments

还有 3 个错误为:Cannot convert int to byte.

那么 MSDN 示例是如何工作的呢?

【问题讨论】:

  • 太愚蠢了,他们不允许默认的#FFFFFF 格式。
  • 这些都不适用于 UWP

标签: wpf


【解决方案1】:

试试这个:

(SolidColorBrush)new BrushConverter().ConvertFrom("#ffaacc");

【讨论】:

    【解决方案2】:

    我一直在使用:

    new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));
    

    【讨论】:

      【解决方案3】:

      如果您不想每次都处理转换的痛苦,只需创建一个扩展方法。

      public static class Extensions
      {
          public static SolidColorBrush ToBrush(this string HexColorString)
          {
              return (SolidColorBrush)(new BrushConverter().ConvertFrom(HexColorString));
          }    
      }
      

      然后像这样使用:BackColor = "#FFADD8E6".ToBrush()

      如果您可以提供一种方法来做同样的事情,或者。

      public SolidColorBrush BrushFromHex(string hexColorString)
      {
          return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexColorString));
      }
      
      BackColor = BrushFromHex("#FFADD8E6");
      

      【讨论】:

        【解决方案4】:
        using System.Windows.Media;
        
        byte R = Convert.ToByte(color.Substring(1, 2), 16);
        byte G = Convert.ToByte(color.Substring(3, 2), 16);
        byte B = Convert.ToByte(color.Substring(5, 2), 16);
        SolidColorBrush scb = new SolidColorBrush(Color.FromRgb(R, G, B));
        //applying the brush to the background of the existing Button btn:
        btn.Background = scb;
        

        【讨论】:

          【解决方案5】:

          How to get Color from Hexadecimal color code using .NET?

          我认为这就是你所追求的,希望它能回答你的问题。

          要让您的代码正常工作,请使用 Convert.ToByte 而不是 Convert.ToInt...

          string colour = "#ffaacc";
          
          Color.FromRgb(
          Convert.ToByte(colour.Substring(1,2),16),
          Convert.ToByte(colour.Substring(3,2),16),
          Convert.ToByte(colour.Substring(5,2),16));
          

          【讨论】:

            【解决方案6】:

            vb.net版

            Me.Background = CType(New BrushConverter().ConvertFrom("#ffaacc"), SolidColorBrush)
            

            【讨论】:

              猜你喜欢
              • 2016-06-08
              • 1970-01-01
              • 2014-06-12
              • 1970-01-01
              • 2014-08-19
              • 1970-01-01
              • 2019-06-16
              • 2021-03-08
              • 2016-09-25
              相关资源
              最近更新 更多