如何将画刷(例如DrawingBrush)转换为位图源(BitmapSource)?

7

我有一个包含一些矢量图形的DrawingBrush。我想将其转换为BitmapSource,作为将其转换为位图的中间步骤。怎样(最好地)实现这一点?

1个回答

12
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;
}

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