2016-01-29 160 views
2

我正在使用C#WPF,並試圖從3D模型渲染2D視圖,我可以將其用作我的UI項目的預覽圖像。從model3dgroup的3D模型將圖像渲染爲位圖失敗

爲了實現這個目標,我想正確使用這個類:

RenderTargetBitmap類https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap(v=vs.110).aspx

這是我嘗試使用它:

無關緊要,因爲更新

public void SetModelImage() 
    { 
     RenderTargetBitmap bmp = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32); 
     PngBitmapEncoder png = new PngBitmapEncoder(); 
     Viewport3D myViewport3d = new Viewport3D(); 
     ModelVisual3D myModelVisual3D = new ModelVisual3D(); 
     Model3DGroup myModel3DGroup = new Model3DGroup(); 
     GeometryModel3D myGeometryModel = new GeometryModel3D(); 
     this.previewModel = new PngBitmapEncoder(); 
     PerspectiveCamera myPCamera = new PerspectiveCamera(); 

     myModel3DGroup.Children.Add(this.content);// ajoute le modele 
     myModelVisual3D.Content = myModel3DGroup; 
     myModelVisual3D.Content = this.content; 
     myViewport3d.Children.Add(myModelVisual3D); 
     bmp.Render(myViewport3d); 

     this.previewModel.Frames.Add(BitmapFrame.Create(bmp)); 

     string filepath = "C:\\Users\\Remi\\Desktop\\toto.png"; 
     using (Stream stm = File.Create(filepath)) 
     { 

      this.previewModel.Save(stm); 

     } 

    } 

The 問題是生成的Bitpmap全黑

全部文件pastbin: http://paste.isomorphis.me/jgz

感謝您的時間! :)

UPDATE: 多虧了我已經糾正了我初始化的佈局方式與measurearrangeInvalidateVisual但我仍然有生成的黑位圖的建議。 enter image description here

回答

1

你必須通過調用其MeasureArrange方法來運行Viewport3D元素的初始佈局。您可能還需要致電InvalidateVisual

myViewport3d.Children.Add(myModelVisual3D); 
myViewport3d.Measure(new Size(200, 200)); 
myViewport3d.Arrange(new Rect(0, 0, 200, 200)); 
myViewport3d.InvalidateVisual(); 
bmp.Render(myViewport3d); 
+0

我編輯了我的問題,謝謝! – Folder

+0

還沒有InvalidateVisual() 發佈和截圖已更新,謝謝! – Folder