如何将System.Windows.Media.Brush转换为System.Drawing.Brush的C#方法

5

我想给一个TextBox添加水印。TextBox.Background是System.Windows.Media.Brush类型的,我需要使用Graphics.FillRectangle(System.Drawing.Brush....)方法。

有没有办法将media brush转换为drawing brush?


我不这么认为。它们基于两个大部分不兼容的框架,是完全不兼容的两件事情。 - vcsjones
1
可能是重复的问题 https://dev59.com/D0jSa4cB1Zd3GeqPDCuG - Alberto
2个回答

10

试着用这个

System.Drawing.Brush b = new System.Drawing.SolidBrush((System.Drawing.Color)new System.Drawing.ColorConverter().ConvertFromString(new System.Windows.Media.BrushConverter().ConvertToString(mediabrush)));

嗨,Sam,我也可以问一下如何将十六进制颜色转换为System.Drawing.Brushes吗? - Payson
尝试使用以下代码 System.Drawing.ColorTranslator.FromHtml("hexcolor"); 或者像我这样使用 (System.Drawing.Color)new System.Drawing.ColorConverter().ConvertFromString("hexcolor"); 来转换颜色。 - Sam

1
这也适用于UWP和WinUI。用法:
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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接