【问题标题】:How to take a screenshot of a WPF control?如何截取 WPF 控件的屏幕截图?
【发布时间】:2014-08-19 10:17:46
【问题描述】:

我使用 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,结果是一样的。

【问题讨论】:

标签: c# .net wpf screenshot system.drawing


【解决方案1】:

屏幕截图是屏幕截图...屏幕上的所有内容。您想要的是从单个UIElement 保存图像,您可以使用RenderTargetBitmap.Render Method 来做到这一点。此方法采用Visual 输入参数,幸运的是,它是所有UIElements 的基类之一。所以假设你想保存一个 .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);
}

【讨论】:

  • 如果我想在image控件中显示这个pngImage而不是保存pngImage怎么办
  • @UzairAli,这要简单得多。只需使用要显示为VisualVisualBrush 的控件。有关详细信息,请参阅 MSDN 上的 VisualBrush Class 页面。
  • VisualTreeHelper.GetDescendantBounds 将帮助您获得任何Visual 的尺寸。它返回Rect,其WidthHeight 是双精度数;您需要使用Convert.ToInt32 转换它们。
  • 值得一提的是PixelFormats.Pbgra32是这里唯一支持的格式。您可以更隐含地将其指定为PixelFormats.Default
  • int width = Convert.ToInt32(dtgEvolucaoPendenciasDiretoria.ActualWidth); int height = Convert.ToInt32(dtgEvolucaoPendenciasDiretoria.ActualHeight); RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); PngBitmapEncoder pngImage = new PngBitmapEncoder(); renderTargetBitmap.Render(dtgEvolucaoPendenciasDiretoria); pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));使用 (Stream fileStream = File.Create(@"D:\Users\dtgEvolucaoPendenciasDiretoria.bmp")) { pngImage.Save(fileStream); }
猜你喜欢
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多