在图像中有一个意外的透明区域,RenderTargetBitmap捕获了wpf控件

时间:2017-05-05 09:04:06

标签: wpf screen capture rendertargetbitmap

我试图通过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);
            }
    }

Captured image has transparent part at bottom

1 个答案:

答案 0 :(得分:0)

一个窗口的ActualWidthActualHeight包含边框和标题栏的大小。

您应该渲染其顶级子元素,即Content

,而不是Window
var contentElement = (FrameworkElement)Content;

var renderTargetBitmap = new RenderTargetBitmap(
    (int)contentElement.ActualWidth, (int)contentElement.ActualHeight,
    96, 96, PixelFormats.Default);

renderTargetBitmap.Render(contentElement);