Creating SolidColorBrush from hex color value

后端 未结 6 1490
挽巷
挽巷 2020-12-12 14:59

I want to create SolidColorBrush from Hex value such as #ffaacc. How can I do this?

On MSDN, I got :

SolidColorBrush mySolidColorBrush = new SolidCol         


        
相关标签:
6条回答
  • 2020-12-12 15:02

    If you don't want to deal with the pain of the conversion every time simply create an extension method.

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

    Then use like this: BackColor = "#FFADD8E6".ToBrush()

    Alternately if you could provide a method to do the same thing.

    public SolidColorBrush BrushFromHex(string hexColorString)
    {
        return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexColorString));
    }
    
    BackColor = BrushFromHex("#FFADD8E6");
    
    0 讨论(0)
  • 2020-12-12 15:06

    Try this instead:

    (SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));
    
    0 讨论(0)
  • 2020-12-12 15:07

    I've been using:

    new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));
    
    0 讨论(0)
  • How to get Color from Hexadecimal color code using .NET?

    This I think is what you are after, hope it answers your question.

    To get your code to work use Convert.ToByte instead of 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));
    
    0 讨论(0)
  • 2020-12-12 15:21
    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;
    
    0 讨论(0)
  • 2020-12-12 15:26

    vb.net version

    Me.Background = CType(New BrushConverter().ConvertFrom("#ffaacc"), SolidColorBrush)
    
    0 讨论(0)
提交回复
热议问题