使用下面的代碼,我試圖用UIElements填充Canvas
並將其保存爲tif Image
。但是,我的Image
總是空白。這是因爲Canvas
永遠不會顯示在屏幕上,並且某種初始化和繪圖從未發生過?我該如何做這項工作?創建VisualBrush而不會顯示它代表的視覺
的Canvas
創作會去是這樣的:
Canvas theCanvas = new Canvas();
theCanvas.Width = 2740;
theCanvas.Height = 2280;
...
Button button = new Button();
button.Content = "Push Me.";
button.Height = 50;
button.Width = 200;
Canvas.SetTop(button, 200);
Canvas.SetLeft(button, 300);
theCanvas.Children.Add(button);
要創建Image
並保存:
using (System.IO.FileStream fs =
new System.IO.FileStream(path, System.IO.FileMode.Create))
{
RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
(int)inWidth,
(int)inHeight, 1/300, 1/300,
PixelFormats.Pbgra32);
DrawingVisual visual = new DrawingVisual();
using (DrawingContext context = visual.RenderOpen())
{
VisualBrush brush = new VisualBrush(inCanvas);
context.DrawRectangle(
brush,
null,
new Rect(new Point(), new Size(inWidth, inHeight)));
}
renderBitmap.Render(visual);
BitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
encoder.Save(fs);
fs.Close();
}
我有同樣的問題。 http://stackoverflow.com/questions/1877115/create-wpf-element-offscreen-and-render-to-bitmap – Will 2010-02-04 20:16:59
那麼,可能是一個差異問題(我做錯了什麼),但代碼是所有的.. – Will 2010-02-04 20:19:19
是啊,這有幫助。我錯過了測量和安排。 – 2010-02-05 18:45:15