保存WPF画布图像 [英] Saving a WPF canvas as an image

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

问题描述

我在下面的文章我得到了我的画布被保存,但是,我想延长code的功能和我的画布的特定部分保存为图像,而不是我的整个画布。

I was following this article and I got my canvas to be saved, however, I want to extend the code's functionality and save a particular part of my canvas as an image, rather than my entire canvas.

我尝试设置 rect.Offset rect.Location 属性,但图像始终保存从上我的画布的左上角。

I tried setting the rect.Offset and rect.Location properties but the image is always saved from the upper left corner of my canvas.

有谁知道我可以实现我想要的功能,以类似的方式?

Does anyone know how can I achieve my wanted functionality in a similar way?

谢谢!

推荐答案

一个简单的方法是使用一个<一个href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.croppedbitmap.aspx">CroppedBitmap经过渲染整个画布。如果你需要多张图片,你可以重复使用相同的RenderTargetBitmap。

A simple method would be to use a CroppedBitmap after rendering the whole canvas. You could reuse the same RenderTargetBitmap if you need multiple images.

RenderTargetBitmap rtb = new RenderTargetBitmap((int)canvas.RenderSize.Width,
    (int)canvas.RenderSize.Height, 96d, 96d, System.Windows.Media.PixelFormats.Default);
rtb.Render(canvas);

var crop = new CroppedBitmap(rtb, new Int32Rect(50, 50, 250, 250));

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

using(var fs = System.IO.File.OpenWrite("logo.png"))
{
    pngEncoder.Save(fs);
}

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

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