从hex颜色值创buildSolidColorBrush

我想从Hex值(例如#ffaacc)创buildSolidColorBrush。 我怎样才能做到这一点?

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

试试这个:

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

如何使用.NET从hex颜色代码获取颜色?

我想这是你以后的样子,希望能回答你的问题。

要使您的代码工作使用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; 

我一直在使用:

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

在这里,你走,用我的class级多颜色转换

 using System; using System.Windows.Media; using SDColor = System.Drawing.Color; using SWMColor = System.Windows.Media.Color; using SWMBrush = System.Windows.Media.Brush; //Developed by Amin Amiri Darban namespace APREndUser.CodeAssist { public static class ColorHelper { public static SWMColor ToSWMColor(SDColor color) => SWMColor.FromArgb(color.A, color.R, color.G, color.B); public static SDColor ToSDColor(SWMColor color) => SDColor.FromArgb(color.A, color.R, color.G, color.B); public static SWMBrush ToSWMBrush(SDColor color) => (SolidColorBrush)(new BrushConverter().ConvertFrom(ToHexColor(color))); public static string ToHexColor(SDColor c) => "#" + cRToString("X2") + cGToString("X2") + cBToString("X2"); public static string ToRGBColor(SDColor c) => "RGB(" + cRToString() + "," + cGToString() + "," + cBToString() + ")"; public static Tuple<SDColor, SDColor> GetColorFromRYGGradient(double percentage) { var red = (percentage > 50 ? 1 - 2 * (percentage - 50) / 100.0 : 1.0) * 255; var green = (percentage > 50 ? 1.0 : 2 * percentage / 100.0) * 255; var blue = 0.0; SDColor result1 = SDColor.FromArgb((int)red, (int)green, (int)blue); SDColor result2 = SDColor.FromArgb((int)green, (int)red, (int)blue); return new Tuple<SDColor, SDColor>(result1, result2); } } }