wpf 从控制视图获取位图图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2522380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a bitmap image from a Control view
提问by Aurelien Ribon
I would like to "copy to clipboard" what a Control
of my WPF
app draws on the screen.
Therefore, I need to build a bitmap image from my Control current display.
我想“复制到剪贴板”Control
我的WPF
应用程序在屏幕上绘制的内容。因此,我需要从我的控制当前显示中构建一个位图图像。
Is there an easy way to do that ?
有没有一种简单的方法可以做到这一点?
Thanks in advance.
提前致谢。
回答by Bubblewrap
I wouldn't call it easy...but the key component is the RenderTargetBitmap, which you can use as follows:
我不会说这很简单……但关键组件是 RenderTargetBitmap,您可以按如下方式使用它:
RenderTargetBitmap rtb = new RenderTargetBitmap((int)control.ActualWidth, (int)control.ActualHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(control);
Well, that part is easy, now the RTB has the pixels stored internally...but your next step would be putting that in a useful format to place it on the clipboard, and figuring that out can be messy...there are a lot of image related classes that all interact one or another.
嗯,这部分很简单,现在 RTB 已将像素存储在内部……但是您的下一步是将其放入有用的格式中以将其放置在剪贴板上,然后弄清楚可能会很麻烦……有一个许多与图像相关的类都相互作用。
Here's what we use to create a System.Drawing.Image, which i think you should be able to put on the clipboard.
这是我们用来创建 System.Drawing.Image 的内容,我认为您应该可以将其放在剪贴板上。
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(rtb));
MemoryStream stream = new MemoryStream();
png.Save(stream);
Image image = Image.FromStream(stream);
System.Drawing.Image (a forms image) cannot interact directly with the RenderTargetBitmap (a WPF class), so we use a MemoryStream to convert it.
System.Drawing.Image(表单图像)无法直接与 RenderTargetBitmap(WPF 类)交互,因此我们使用 MemoryStream 对其进行转换。
回答by Bj?rn
If the control you are trying to create a bitmap from is inside a StackPanel
it won't work, you will just get an empty image.
如果您尝试从中创建位图的控件位于内部StackPanel
,它将无法工作,您只会得到一个空图像。
Jaime Rodriguez has a good piece of code to get around this on his blog:
Jaime Rodriguez 在他的博客上有一段很好的代码来解决这个问题:
private static BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY)
{
if (target == null)
{
return null;
}
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
(int)(bounds.Height * dpiY / 96.0),
dpiX,
dpiY,
PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
}
rtb.Render(dv);
return rtb;
}