21

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

为了重现,创建一个简单的 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 保存到磁盘,它的大小正确但透明。

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

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

4

1 回答 1

27

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

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

(不需要调用 UpdateLayout。)

于 2009-12-09T23:49:19.997 回答