使用RenderTargetBitmap的WPF画布区域的快照 [英] Snapshot of an WPF Canvas Area using RenderTargetBitmap

查看:491
本文介绍了使用RenderTargetBitmap的WPF画布区域的快照的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中创建画布区域的快照.我正在使用可视笔刷获取快照,并使用PngEncoder将其保存.但是生成的PNG只是一个空的黑色图像.我不确定问题出在创建的BitmapSource还是PNGEncoder问题.这是我用来获取相同代码的代码.

I want to create a Snapshot of the Canvas Area in my Application. I'm using Visual brush to get the Snapshot and saving the same using PngEncoder. But the resulting PNG is just a empty black image. I'm not sure the issue is with the BitmapSource created or the PNGEncoder issue. Here is the code I'm using to obtain the same.

public void ConvertToBitmapSource(UIElement element)
{
    var target = new RenderTargetBitmap((int)(element.RenderSize.Width), (int)(element.RenderSize.Height), 96, 96, PixelFormats.Pbgra32);
    var brush = new VisualBrush(element);

    var visual = new DrawingVisual();
    var drawingContext = visual.RenderOpen();


    drawingContext.DrawRectangle(brush, null, new Rect(new Point(0, 0),
    new Point(element.RenderSize.Width, element.RenderSize.Height)));

    drawingContext.Close();

    target.Render(visual);

    PngBitmapEncoder encoder = new PngBitmapEncoder();
    BitmapFrame outputFrame = BitmapFrame.Create(target);
    encoder.Frames.Add(outputFrame);
    using (FileStream file = File.OpenWrite("TestImage.png"))
    {
         encoder.Save(file);
    }

}   

推荐答案

不确定为什么您的代码无法正常工作.这有效:

Not sure why exactly your code isn't working. This works:

public void WriteToPng(UIElement element, string filename)
{
    var rect = new Rect(element.RenderSize);
    var visual = new DrawingVisual();

    using (var dc = visual.RenderOpen())
    {
        dc.DrawRectangle(new VisualBrush(element), null, rect);
    }

    var bitmap = new RenderTargetBitmap(
        (int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Default);
    bitmap.Render(visual);

    var encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bitmap));

    using (var file = File.OpenWrite(filename))
    {
        encoder.Save(file);
    }
}

这篇关于使用RenderTargetBitmap的WPF画布区域的快照的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆