【问题标题】:Create WPF element offscreen and render to bitmap在屏幕外创建 WPF 元素并渲染到位图
【发布时间】:2010-12-25 00:41:34
【问题描述】:

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

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

    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 保存到磁盘,它的大小正确但透明。

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

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

【问题讨论】:

    标签: wpf rendertargetbitmap


    【解决方案1】:

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

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

    (不需要调用 UpdateLayout。)

    【讨论】:

    • 一个........当我开始尝试完成此操作时,我检查了 DesiredSize 一次,它不是 0,0(谁知道为什么)并且从未检查过它再次。谢谢!
    • 我们刚刚发现,如果您在控件内将 ItemsControls 绑定到它们的 ItemsSources,您将在屏幕外渲染,您似乎必须调用 UpdateLayout() 否则它们不会渲染任何项目。
    • UpdateLayout 似乎也是渲染 DiffuseMaterial 所必需的。它必须做的比它的名字所暗示的要多。
    • 太棒了。你刚刚救了我的命。
    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    相关资源
    最近更新 更多