'C# how to convert system.windows.media.brush to system.drawing.brush
I am trying to add a watermark for a TextBox. The TextBox.Background is a System.Windows.Media.Brush. I need the Graphics.FillRectangle(System.Drawing.Brush....)
Is there any way to convert the mediea brush to the drawing brush?
Solution 1:[1]
Try with this
System.Drawing.Brush b = new System.Drawing.SolidBrush((System.Drawing.Color)new System.Drawing.ColorConverter().ConvertFromString(new System.Windows.Media.BrushConverter().ConvertToString(mediabrush)));
Solution 2:[2]
This will also work for UWP and WinUI. Usage:
var newBrush = new System.Drawing.SolidBrush(brush.ToSystemDrawingColor())
internal static System.Drawing.Color ToSystemDrawingColor(this Brush? brush)
{
if (brush == null)
{
return System.Drawing.Color.Transparent;
}
if (brush is not SolidColorBrush solidColorBrush)
{
throw new NotImplementedException();
}
var color = solidColorBrush.Color;
return System.Drawing.Color.FromArgb(
alpha: color.A,
red: color.R,
green: color.G,
blue: color.B);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Konstantin S. |