Snapshot of an WPF Canvas Area using RenderTargetBitmap

前端 未结 2 950
春和景丽
春和景丽 2020-12-02 00:57

I want to create a Snapshot of the Canvas Area in my Application. I\'m using Visual brush to get the Snapshot and saving the same using PngEncoder. But the resulting PNG is

2条回答
  •  执笔经年
    2020-12-02 01:03

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

提交回复
热议问题