C# 如何将 system.windows.media.brush 转换为 system.drawing.brush

本文关键字:system brush 转换 drawing media windows | 更新日期: 2023-09-27 18:36:41

我正在尝试为文本框添加水印。TextBox.Background 是一个 System.Windows.Media.Brush。我需要Graphics.FillRectangle(System.Drawing.Brush....)

有没有办法将地中海画笔转换为绘图画笔?

C# 如何将 system.windows.media.brush 转换为 system.drawing.brush

试试这个

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

这也适用于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);
}