我不明白为什么这不起作用,或者我需要什么才能让它起作用。
为了重现,创建一个简单的 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 保存到磁盘,它的大小正确但透明。
但是,如果我使用屏幕上显示的视觉效果来执行此操作,则效果很好。
如何将我在屏幕外构建的视觉效果渲染到位图?