2011-08-12 84 views
3

我正在使用此代碼WPF控件的圖像:獲取圖像被裁剪到顯示尺寸

BitmapEncoder imgEncoder = new PngBitmapEncoder(); 
RenderTargetBitmap bmpSource = new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 150, 150, PixelFormats.Pbgra32); 
bmpSource.Render(element); 
imgEncoder.Frames.Add(BitmapFrame.Create(bmpSource)); 
using (MemoryStream ms = new MemoryStream()) 
{ 
    imgEncoder.Save(ms); 
    bytes = ms.ToArray(); 
    ms.Position = 0; 
    Image i = Image.FromStream(ms); 
    i.Save(@"C:\" + Guid.NewGuid().ToString() + "LARGE.png"); 
} 

麻煩的是ActualHeight/Width屬性給出的呈現高度和寬度,即所顯示的部分。即使某些控件在屏幕上不可見,即將其放置在滾動查看器中,我仍想保存整個控件的圖像。

如何獲取控件的完整大小/高度,以便bmpSource.Render()將整個控件呈現給圖像?

回答

0

您可以嘗試暫時將控件從其上下文中取出(可能會導致出現問題),將其轉換爲可見點或將其滾動到視圖中進行呈現。

+0

你是什麼意思可見點,我試着給它一個新的大小和調用updatelayout(),但它恢復到其舊的大小? – Jon

+0

可見點是保證可見的任何點,使用滾動查看器通常比將控件移動到視口更容易滾動視口。 –

1
 private static void SaveUsingEncoder(string fileName, FrameworkElement UIElement, BitmapEncoder encoder) 
    { 
     int height = (int)UIElement.ActualHeight; 
     int width = (int)UIElement.ActualWidth; 

     // These two line of code make sure that you get completed visual bitmap. 
     // In case your Framework Element is inside the scroll viewer then some part which is not 
     // visible gets clip. 
     UIElement.Measure(new System.Windows.Size(width, height)); 
     UIElement.Arrange(new Rect(new System.Windows.Point(), new Point(width, height))); 

     RenderTargetBitmap bitmap = new RenderTargetBitmap(width, 

                   height, 
                   96, // These decides the dpi factors 
                   96,// The can be changed when we'll have preview options. 
                   PixelFormats.Pbgra32); 
     bitmap.Render(UIElement); 

     SaveUsingBitmapTargetRenderer(fileName, bitmap, encoder); 
    } 


    private static void SaveUsingBitmapTargetRenderer(string fileName, RenderTargetBitmap renderTargetBitmap, BitmapEncoder bitmapEncoder) 
    { 
     BitmapFrame frame = BitmapFrame.Create(renderTargetBitmap); 
     bitmapEncoder.Frames.Add(frame); 
     // Save file . 
     using (var stream = File.Create(fileName)) 
     { 
      bitmapEncoder.Save(stream); 
     } 
    } 

調用該函數

 SaveUsingEncoder(fileName, frameworkElement, new PngBitmapEncoder()); 

希望這會有所幫助。