18
我不明白爲什麼這不起作用,或者我需要讓它工作。創建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保存到磁盤,則其大小正確但透明。
但是,如果我在屏幕上顯示的視覺效果,它可以正常工作。
我該如何渲染一個我已經構造的離線位圖的視覺?
的兒子........我檢查DesiredSize一次回來的路上時,我就開始嘗試做到這一點,並它不是0.0(誰知道爲什麼),也從來沒有再檢查過它。謝謝! – Will 2009-12-10 13:37:59
我們只是發現,如果你在控件的ItemsSources中綁定了ItemsControls,那麼你將不得不調用'UpdateLayout()'或者它們不渲染任何項目。 – 2012-11-07 09:52:16