wpf - 如何从 Brush(例如 DrawingBrush)转换为 BitmapSource?

标签 wpf bitmapsource drawingbrush

我有一个带有矢量图形的 DrawingBrush。我想将其转换为 BitmapSource 作为将其转换为 Bitmap 的中间步骤。这样做的(最佳)方法是什么?

最佳答案

public static BitmapSource BitmapSourceFromBrush(Brush drawingBrush, int size = 32, int dpi = 96)
{
    // RenderTargetBitmap = builds a bitmap rendering of a visual
    var pixelFormat = PixelFormats.Pbgra32;
    RenderTargetBitmap rtb = new RenderTargetBitmap(size, size, dpi, dpi, pixelFormat);

    // Drawing visual allows us to compose graphic drawing parts into a visual to render
    var drawingVisual = new DrawingVisual();
    using (DrawingContext context = drawingVisual.RenderOpen())
    {
        // Declaring drawing a rectangle using the input brush to fill up the visual
        context.DrawRectangle(drawingBrush, null, new Rect(0, 0, size, size));
    }

    // Actually rendering the bitmap
    rtb.Render(drawingVisual);
    return rtb;
}

关于wpf - 如何从 Brush(例如 DrawingBrush)转换为 BitmapSource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7038079/

相关文章:

WPF 和 MVVM 问题

c# - Caliburn Micro MVVM INotifyPropertyChanged

c# - 在 C# 中创建一个空的 BitmapSource

javascript - HTML5 Canvas javascript 涂抹画笔工具

c# - WPF 像素网格线

wpf - Silverlight 4等效于WPF “x:static”

c# - 使用 VisualBrush 获取 WPF 区域的 System.Drawing.Bitmap

c# - 如何读取 BitmapSource 四个角的像素?

wpf - 如何以编程方式创建/填充关于 MVVM 的 View ?