在屏幕外创建 WPF 元素并渲染到位图 [英] Create WPF element offscreen and render to bitmap

查看:21
本文介绍了在屏幕外创建 WPF 元素并渲染到位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这不起作用,或者我需要什么才能让它工作.

I can't understand why this doesn't work, or what I need to get it to work.

要重现,请创建一个简单的 WPF 应用程序并以此方式替换主窗口的构造函数:

To repro, create a simple WPF application and replace the main window's constructor thusly:

    public MainWindow()
    {
        InitializeComponent();

        // simple visual definition
        var grid = new Grid { Width = 300, Height = 300 };
        var text = new TextBlock 
                       { 
                         Text = "Y DON'T I WORK???", 
                         FontSize = 100, 
                         FontWeight = 
                         FontWeights.Bold 
                       };
        grid.Children.Add(text);

        // update the layout so everything is awesome cool
        grid.Measure(grid.DesiredSize);
        grid.Arrange(new Rect(grid.DesiredSize));
        grid.UpdateLayout();

        // create a BitmapSource from the visual
        var rtb = new RenderTargetBitmap(
                                    (int)grid.Width,
                                    (int)grid.Height,
                                    96,
                                    96,
                                    PixelFormats.Pbgra32);
        rtb.Render(grid);

        // Slap it in the window
        this.Content = new Image { Source = rtb, Width = 300, Height = 300 };
    }

这会导致图像为空.如果我将 RTB 以 PNG 格式保存到磁盘,则其大小正确但透明.

This results in an empty image. If I save the RTB to disk as a PNG its the correct size but transparent.

但是,如果我使用屏幕上显示的视觉效果来执行此操作,则效果很好.

If, however, I do this with a visual that's been displayed on screen, it works fine.

如何将我在屏幕外构建的视觉效果渲染为位图?

推荐答案

因为在您测量元素之前,元素没有所需的大小.您告诉网格使用 0x0 的可用空间调整自身大小.将您的代码更改为:

Because elements don't have a desired size until you measure them. You were telling the Grid to size itself with an available space of 0x0. Change your code to:

grid.Measure(new Size(grid.Width, grid.Height));
grid.Arrange(new Rect(new Size(grid.Width, grid.Height)));

(不需要调用 UpdateLayout.)

(The call to UpdateLayout is unneeded.)

这篇关于在屏幕外创建 WPF 元素并渲染到位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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