我试图通过RenderTargetBitmap类将主窗口wpf应用程序捕获到png图像。除了图像底部和左侧有一个小透明区域外,它工作得很好。这是代码和捕获的图像:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
string folder = "screenshot";
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
string filename = "ScreenCapture_" + DateTime.Now.ToString("ddMM_hhmmss") + ".png";
string filePath = folder + "//" + filename;
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap((int)this.ActualWidth, (int)this.ActualHeight, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(this);
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
using (Stream fileStream = File.Create(filePath))
{
pngImage.Save(fileStream);
}
}
答案 0 :(得分:0)
一个窗口的ActualWidth
和ActualHeight
包含边框和标题栏的大小。
您应该渲染其顶级子元素,即Content
:
var contentElement = (FrameworkElement)Content;
var renderTargetBitmap = new RenderTargetBitmap(
(int)contentElement.ActualWidth, (int)contentElement.ActualHeight,
96, 96, PixelFormats.Default);
renderTargetBitmap.Render(contentElement);