繁体   English   中英

如何截取 WPF 控件的屏幕截图?

[英]How to take a screenshot of a WPF control?

我使用 Bing 地图 WPF 控件创建了一个 WPF 应用程序。 我希望能够仅对 Bing 地图控件进行截图。

使用此代码制作屏幕截图:

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

我的问题:

WidthHeight似乎不好(错误值)。 生成的屏幕截图似乎使用了错误的坐标。

我的截图:

我的截图

我的期望:

想要的截图

为什么我得到这个结果? 我在 Release 模式下尝试过,没有 Visual Studio,结果是一样的。

屏幕截图是屏幕截图……屏幕上的所有内容 您想要的是从单个UIElement保存图像,您可以使用RenderTargetBitmap.Render Method来做到这一点。 此方法采用Visual输入参数,幸运的是,它是所有UIElement的基类之一。 所以假设你想保存一个 .png 文件,你可以这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM