将画布保存到png C#wpf

时间:2014-01-28 16:54:51

标签: c# wpf png rendertargetbitmap

所以我试图在WPF C#中拍摄我的画布快照,以便我可以将其保存为png。目前图像保存不正确,因为它包括左边距和上边距。

这就是我所拥有的:

为画布大小创建一个矩形。如果canvas.Margin.Left和Top设置为0,则保存的图像大小正确,但仍会出现偏移,从而切割底边和右边。设置Margin.Left和Top仍会导致偏移发生,但整个图像被保存但尺寸错误(margin.Left + ActualWidth)而不仅仅是ActualWidth

Rect rect = new Rect(canvas.Margin.Left, canvas.Margin.Top, canvas.ActualWidth, canvas.ActualHeight);

double dpi = 96d;

RenderTargetBitmap rtb = new RenderTargetBitmap((int)rect.Right, (int)rect.Bottom, dpi, dpi, System.Windows.Media.PixelFormats.Default);

rtb.Render(canvas);

BitmapEncoder pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(rtb));

try
{
    System.IO.MemoryStream ms = new System.IO.MemoryStream();

    pngEncoder.Save(ms);
    ms.Close();

    System.IO.File.WriteAllBytes(filename, ms.ToArray());
}
catch (Exception err)
{
    MessageBox.Show(err.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

1 个答案:

答案 0 :(得分:12)

用这些行替换前四行

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

我已经关注了这篇文章http://mcleodsean.wordpress.com/2008/10/07/bitmap-snapshots-of-wpf-visuals/(有关更多说明),并且能够在没有边距的情况下保存画布。