Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert from a Brush (e.g. DrawingBrush) to a BitmapSource?

I have a DrawingBrush with some vector graphics. I want to convert it to BitmapSource as an intermediate step to getting it to Bitmap. What's the (best) way to do this?

like image 723
Tim Lovell-Smith Avatar asked Aug 12 '11 09:08

Tim Lovell-Smith


1 Answers

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;
}
like image 107
Tim Lovell-Smith Avatar answered Nov 14 '22 18:11

Tim Lovell-Smith