如何截取 WPF 控件的屏幕截图?
我使用 Bing 地图 WPF 控件创建了一个 WPF 应用程序.我希望只能截图 Bing 地图控件.
I created a WPF application using the Bing maps WPF control. I would like to be able to screenshot only the Bing maps control.
是使用此代码制作屏幕截图:
Is use this code to make the screenshot:
// Store the size of the map control
int Width = (int)MyMap.RenderSize.Width;
int Height = (int)MyMap.RenderSize.Height;
System.Windows.Point relativePoint = MyMap.TransformToAncestor(Application.Current.MainWindow).Transform(new System.Windows.Point(0, 0));
int X = (int)relativePoint.X;
int Y = (int)relativePoint.Y;
Bitmap Screenshot = new Bitmap(Width, Height);
Graphics G = Graphics.FromImage(Screenshot);
// snip wanted area
G.CopyFromScreen(X, Y, 0, 0, new System.Drawing.Size(Width, Height), CopyPixelOperation.SourceCopy);
string fileName = "C:\myCapture.bmp";
System.IO.FileStream fs = System.IO.File.Open(fileName, System.IO.FileMode.OpenOrCreate);
Screenshot.Save(fs, System.Drawing.Imaging.ImageFormat.Bmp);
fs.Close();
我的问题:
Width
和 Height
看起来很糟糕(错误值).生成的屏幕截图似乎使用了错误的坐标.
The Width
and Height
appear to be bad (false values).
The screenshot produced appear to use bad coordinates.
我的截图:
我的期望:
为什么我会得到这个结果?我在 Release 模式下试过,没有 Visual Studio,结果是一样的.
Why do I get this result? I tried in Release mode, and without Visual Studio, result is the same.
屏幕截图是屏幕截图...屏幕上的所有内容.您想要的是从单个 UIElement
保存图像,您可以使用 RenderTargetBitmap.Render
方法.这个方法需要一个 Visual
输入参数,幸运的是,它是所有 UIElement
的基类之一.所以假设你想保存一个 .png 文件,你可以这样做:
A screenshot is a shot of the screen... everything on the screen. What you want is to save an image from a single UIElement
and you can do that using the RenderTargetBitmap.Render
Method. This method takes a Visual
input parameter and luckily, that is one of the base classes for all UIElement
s. So assuming that you want to save a .png file, you could do this:
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(yourMapControl);
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
using (Stream fileStream = File.Create(filePath))
{
pngImage.Save(fileStream);
}