2

The point is, that I need to convert to a System.Drawing.Bitmap (.Net Framework 2.0) to get a single frame of an WPF Grid with its content.

I read about VisualBrush and DrawingBrush but I cannot imagine how it should work.

I can convert any WPF BitmapSource into my System.Drawing.Bitmap successfully. But how to receive the BitmapSource from my Grid?

Thanks

Navid Rahmani
  • 7,848
  • 9
  • 39
  • 57
Nasenbaer
  • 4,810
  • 11
  • 53
  • 86

1 Answers1

5

To convert a Visual to BitmapSource you can use RenderTargetBitmap, VisualBrush and DrawingVisual:

public BitmapSource ConvertToBitmapSource(UIElement element)
{
    var target = new RenderTargetBitmap((int)(element.RenderSize.Width), (int)(element.RenderSize.Height), 96, 96, PixelFormats.Pbgra32);
    var brush = new VisualBrush(element);

    var visual = new DrawingVisual();
    var drawingContext = visual.RenderOpen();


    drawingContext.DrawRectangle(brush, null, new Rect(new Point(0, 0),
        new Point(element.RenderSize.Width, element.RenderSize.Height)));

    drawingContext.Close();

    target.Render(visual);

    return target;
}   
Navid Rahmani
  • 7,848
  • 9
  • 39
  • 57
  • This does not work correctly when the size of the control is greater than 2048x2048. The picture is blurry. MSDN about `BitmapCache`: "The cache functions when hardware acceleration is not available. In this case, the bitmap is rendered in software, and the maximum bitmap dimensions are 2048 x 2048." Does anyone know how to increase the cache to the desired size? – Vitaliy Feb 13 '22 at 21:46