将画布保存为PNG C#WPF [英] Saving a canvas to png C# wpf

查看:137
本文介绍了将画布保存为PNG C#WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试在WPF C#中为画布拍摄快照,以便将其另存为png.该图像当前包含左边缘和上边缘,因此无法正确保存.

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 margins.

这就是我所拥有的:

为画布的大小创建一个矩形.如果canvas.Margin.Left和Top设置为0,则保存的图像具有正确的大小,但仍会发生偏移,因此会切割底部和右侧边缘.设置Margin.Left和Top仍然会引起偏移,但是会保存整个图像,但尺寸(margin.Left + ActualWidth)错误,而不仅仅是ActualWidth

create a rectangle for the size of the canvas. if canvas.Margin.Left and Top are set to 0 then the saved image is of the correct size but the offset still occurs and thus cuts the bottom and right edges. Being set the Margin.Left and Top still causes the offset to occur but the whole image is saved but at the wrong size (margin.Left + ActualWidth) rather than just 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);
}

推荐答案

用这些行替换前四行

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/(更多说明),并且能够保存画布而没有边距.

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.

这篇关于将画布保存为PNG C#WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆