在屏幕外创建 WPF 元素并渲染为位图
我不明白为什么这不起作用,或者我需要什么才能让它起作用。
要重现,请创建一个简单的 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 格式保存到磁盘,它的大小正确但透明。
但是,如果我使用屏幕上显示的视觉效果来执行此操作,则效果很好。
如何将我在屏幕外构建的视觉效果渲染为位图?
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:
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为在测量元素之前,它们没有所需的尺寸。您告诉网格使用 0x0 的可用空间调整自身大小。将代码更改为:(
不需要调用 UpdateLayout。)
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:
(The call to UpdateLayout is unneeded.)