Saving a canvas to png C# wpf

后端 未结 1 1548
滥情空心
滥情空心 2021-01-02 12:26

So I am trying to take a snapshot of my canvas in WPF C# so that I can save it out as a png. The image saves incorrectly at present as it is including the left and top margi

相关标签:
1条回答
  • 2021-01-02 13:08

    Replace the first four lines with these lines

    Rect bounds = VisualTreeHelper.GetDescendantBounds(canvas);
    double dpi = 96d;
    
    RenderTargetBitmap rtb = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, dpi, dpi, System.Windows.Media.PixelFormats.Default);
    
    DrawingVisual dv = new DrawingVisual();
    using (DrawingContext dc = dv.RenderOpen())
    {
        VisualBrush vb = new VisualBrush(canvas);
        dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
    }
    
    rtb.Render(dv);
    

    I have followed this article http://mcleodsean.wordpress.com/2008/10/07/bitmap-snapshots-of-wpf-visuals/ (for more explanation) and able to save the canvas without margins.

    0 讨论(0)
提交回复
热议问题