2010-04-01 63 views
6

我試圖創建一些圖表圖像,而沒有在屏幕上顯示這些圖表。我在這裏呆了很長一段時間,並嘗試了很多不同的東西,但似乎沒有任何工作。如果我首先在窗口中顯示圖表,則該代碼完美工作,但如果我沒有將其顯示在窗口中,則位圖僅爲白色並帶有黑色邊框(不知道爲什麼)。ContentControl + RenderTargetBitmap +空圖像

我已經嘗試在渲染並給邊框添加一個綠色邊框之前將圖表添加到邊框。在位圖中,我看到綠色邊框畫筆,然後是黑色邊框和白色背景,但沒有圖表。該圖表並未包含在黑色邊框中,所以我不知道這是從哪裏來的。

我已經嘗試將圖表添加到窗口而不調用window.Show(),並且我只是得到黑色寄宿生和白色背景。但是,如果我調用window.Show(),則位圖包含圖表。

我已經嘗試使用drawingVisual解釋爲here,結果相同。

下面是代碼(不包括添加元素到一個邊界或窗口):

private static BitmapSource CreateElementScreenshot(FrameworkElement element, int dpi) 
{ 
    if (!element.IsMeasureValid) 
    { 
     Size size = new Size(element.Width, element.Height); 
     element.Measure(size); 
     element.Arrange(new Rect(size)); 
    } 

    element.UpdateLayout(); 

    var scale = dpi/96.0; 

    var renderTargetBitmap = new RenderTargetBitmap 
     (
      (int)(scale * element.RenderSize.Width),(int)(scale * element.RenderSize.Height),dpi,dpi,PixelFormats.Default 
     ); 

    // this is waiting for dispatcher to perform measure, arrange and render passes 
    element.Dispatcher.Invoke(((Action)(() => renderTargetBitmap.Render(element))), DispatcherPriority.Render); 

    return renderTargetBitmap; 
} 

注意:圖表是一個ContentControl中。

無論如何我可以讓圖表呈現而不先在窗口中顯示它?

回答

5

調用element.ApplyTemplate()的竅門。

+1

這不適合我。你在哪裏在你的代碼中插入了ApplyTemplate? – 2012-04-18 10:34:46

+0

抱歉已經過了兩年,因爲我回答了這個問題,並且我無法再訪問該代碼。嘗試在UpdateLayout之前添加它 – Kelly 2012-04-20 20:55:33

+0

感謝您發佈答案。你救了我很多麻煩! :) – ihake 2014-04-18 00:19:13

1

如果有人有呈現類似的問題RenderTargetBitmap(獲得白/空圖像)是在StackPanel中,你可以暫時將其移動到電網,然後渲染並把它放回StackPanel中

項目
Grid grid = new System.Windows.Controls.Grid() { Background = Brushes.White, Width = iWidth, Height = iHeight }; 
Panel panel = plot.Parent as Panel; 

if (panel != null) 
{ 
    panel.Children.Remove(plot); 
    grid.Children.Add(plot); 

    grid.Measure(new Size(iWidth, iHeight)); 
    grid.Arrange(new Rect(new Size(iWidth, iHeight))); 
} 
plot.Measure(new Size(iWidth, iHeight)); 
plot.Arrange(new Rect(new Size(iWidth, iHeight))); 

plot.ApplyTemplate(); 
plot.UpdateLayout(); 

grid.ApplyTemplate(); 
grid.UpdateLayout(); 

RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(
    iWidth, 
    iHeight, 
    96, 96, PixelFormats.Pbgra32); 
renderTargetBitmap.Render(grid); 

PngBitmapEncoder encoder = new PngBitmapEncoder(); 
encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); 

MemoryStream memoryStream = new MemoryStream(); 
encoder.Save(memoryStream); 
bitmap = new System.Drawing.Bitmap(memoryStream); 

if (panel != null) 
{ 
    grid.Children.Remove(plot); 
    panel.Children.Add(plot); 
} 

plot.Measure(new Size(iWidthBefore, iHeightBefore)); 
plot.Arrange(new Rect(new Size(iWidthBefore, iHeightBefore))); 
plot.UpdateLayout(); 
+0

感謝您的提示。我發現了一篇關於這個博客文章以及我在另一個SO線程中記錄的文章:http://stackoverflow.com/questions/2522380/get-a-bitmap-image-from-a-control-view/28626055#28626055 – 2015-02-20 09:56:07

1

對我來說,調用element.Arrange()是缺失的一塊。

+0

我也是。其他建議都沒有奏效。 – brianberns 2016-03-30 06:08:39