I can't understand why this doesn't work, or what I need to get it to work.
我无法理解为什么这不起作用,或者我需要它才能使它工作。
To repro, create a simple WPF application and replace the main window's constructor thusly:
要重新编写,请创建一个简单的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 };
}
This results in an empty image. If I save the RTB to disk as a PNG its the correct size but transparent.
这导致空图像。如果我将RTB作为PNG保存到磁盘,其大小正确但透明。
If, however, I do this with a visual that's been displayed on screen, it works fine.
但是,如果我使用已在屏幕上显示的视觉效果执行此操作,则可以正常工作。
How can I render a visual I've constructed offscreen to a bitmap?
如何渲染我在屏幕外构建位图的视觉效果?
1 个解决方案
#1
24
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使用可用空间0x0调整自身大小。将您的代码更改为:
grid.Measure(new Size(grid.Width, grid.Height));
grid.Arrange(new Rect(new Size(grid.Width, grid.Height)));
(The call to UpdateLayout is unneeded.)
(不需要调用UpdateLayout。)
#1
24
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使用可用空间0x0调整自身大小。将您的代码更改为:
grid.Measure(new Size(grid.Width, grid.Height));
grid.Arrange(new Rect(new Size(grid.Width, grid.Height)));
(The call to UpdateLayout is unneeded.)
(不需要调用UpdateLayout。)