Snapshot of an WPF Canvas Area using RenderTargetBitmap

假如想象 提交于 2019-11-27 09:33:22

Not sure why exactly your code isn't working. This works:

public void WriteToPng(UIElement element, string filename)
{
    var rect = new Rect(element.RenderSize);
    var visual = new DrawingVisual();

    using (var dc = visual.RenderOpen())
    {
        dc.DrawRectangle(new VisualBrush(element), null, rect);
    }

    var bitmap = new RenderTargetBitmap(
        (int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Default);
    bitmap.Render(visual);

    var encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bitmap));

    using (var file = File.OpenWrite(filename))
    {
        encoder.Save(file);
    }
}

Thank you both for the question and the answer.

For the benefit of the others looking for the same answer

I found that Clemens way leaves a black band in the image with the image shifted either down or right. As if it was not rendering the element at the correct position in the bitmap.

So I had to use the VisualBrush as Amar suggested.

Here is the code that worked for me:

    RenderTargetBitmap RenderVisual(UIElement elt)
    {
        PresentationSource source = PresentationSource.FromVisual(elt);
        RenderTargetBitmap rtb = new RenderTargetBitmap((int)elt.RenderSize.Width,   
              (int)elt.RenderSize.Height, 96, 96, PixelFormats.Default);

        VisualBrush sourceBrush = new VisualBrush(elt);
        DrawingVisual drawingVisual = new DrawingVisual();
        DrawingContext drawingContext = drawingVisual.RenderOpen();
        using (drawingContext)
        {
            drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), 
                  new Point(elt.RenderSize.Width, elt.RenderSize.Height)));
        }
        rtb.Render(drawingVisual);

        return rtb;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!