convert from Color to brush

How do I convert a Color to a Brush in C#?

178853 次浏览

这是从 ColorBrush

你不能转换它,你必须做一个新的刷子... 。

SolidColorBrush brush = new SolidColorBrush( myColor );

现在,如果您在 XAML 中需要它,您可以制作一个自定义值转换器并在绑定中使用它

Brush brush = new SolidColorBrush(color);

反过来说:

if (brush is SolidColorBrush colorBrush)
Color color = colorBrush.Color;

或者类似的东西。

Point being not all brushes are colors but you could turn all colors into a (SolidColor)Brush.

SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )

你可以用这个:

new SolidBrush(color)

颜色是这样的:

Color.Red

or

Color.FromArgb(36,97,121))

或者..。

If you happen to be working with a application which has a mix of Windows Forms and WPF you might have the additional complication of trying to convert a System.Drawing.Color to a System.Windows.Media.Color. 我不知道是否有更简单的方法,但我是这样做的:

System.Drawing.Color MyColor = System.Drawing.Color.Red;
System.Windows.Media.Color = ConvertColorType(MyColor);


System.Windows.Media.Color ConvertColorType(System.Drawing.Color color)
{
byte AVal = color.A;
byte RVal = color.R;
byte GVal = color.G;
byte BVal = color.B;


return System.Media.Color.FromArgb(AVal, RVal, GVal, BVal);
}

然后,您可以使用前面提到的技术之一转换为画笔。

通常使用兄弟或父亲的画笔就足够了,在 wpf 中可以通过检索前景或背景属性轻松实现这一点。

档号: 控制中心,背景

我以前也遇到过同样的问题,这是我的课程,它解决了颜色转换问题 Use it and enjoy :

在这里你去,使用我的类多色转换

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 امین امیری دربان
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) => "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
public static string ToRGBColor(SDColor c) => "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
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);
}
}


}

Here is the Easiest way, No Helpers, No Converters, No weird Media references. Just 1 line:

System.Drawing.Brush _Brush = new SolidBrush(System.Drawing.Color.FromArgb(this.ForeColor.R, this.ForeColor.G, this.ForeColor.B));