从十六进制颜色值创建 SolidColorBrush

我想创建 SolidColorBrush 从十六进制值,如 # ffacc。我该如何做到这一点?

在 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 的例子是如何工作的呢?

161034 次浏览

如何使用.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));
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;

试试这个:

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

我一直在用:

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

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

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

Vb.net 版本

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