如何在代码中动态计算WPF所有摄像机设置?

qak*_*mak 9 .net c# wpf

我在Window中有Viewport3D.当窗口大小改变时,它将改变大小.

<Window>
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="100"/>
      <RowDefinition/>
    <Grid.RowDefinitions>
    <Label Grid.Row="0" Content="top label"/>
    <Viewport3D Grid.Row="1" x:Name="vp3D" >
            <Viewport3D.Camera >
                 <PerspectiveCamera x:Name="pCamera"  LookDirection="0 0 -1" UpDirection="0 1 0" />
            </Viewport3D.Camera>
            <Viewport2DVisual3D x:Name="v2dv3d">
                  <Viewport2DVisual3D.Geometry>
                      <MeshGeometry3D x:Name="mg3d" TextureCoordinates="0,0 0,1 1,1 1,0" TriangleIndices="0 1 2 0 2 3"/>
                   </Viewport2DVisual3D.Geometry>
                   <Viewport2DVisual3D.Material>
                         <DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial="True" Brush="White"/>
                   </Viewport2DVisual3D.Material>

                          <Image  Height="{Binding ElementName=vp3D, Path=ActualHeight}" Width="{Binding ElementName=vp3D, Path=ActualWidth}" Stretch="Fill"/>

            </Viewport2DVisual3D>
            <ModelVisual3D>
                 <ModelVisual3D.Content>
                      <DirectionalLight Color="#FFFFFFFF" Direction="0,0,-1"/>
                 </ModelVisual3D.Content>
           </ModelVisual3D>
  </Viewport3D>
 </Grid>
</Window
Run Code Online (Sandbox Code Playgroud)

现在我希望图像显示就像它是原始的2d窗口(看起来没什么变化,但实际上图像是3d).

但问题是如果我希望它看起来与WPF原始相同,我必须更改一些相机设置,如PerspectiveCamera.PositionMeshGeometry3D.Position.因为Viewport3D当窗口改变大小时会动态改变大小,我必须动态计算Viewport3D设置.反正有吗?

我已经尝试过了,但无法正确计算: WPF 3D:使用PerspectiveCamera将整个图像拟合到视图中

qak*_*mak 2

我自己完成。

// get the Viewport3D size first, If you want to use .ActualWidth or .ActualHeight property get it, make sure your application loaded finish, otherwise it will return 0.
double height = ; // get the Viewport3D height or calculate the height first
double width = ; //  get the Viewport3D width or calculate the width first


mg3d.Positions.Clear();
mg3d.Positions.Add(new Point3D(-width, height, 0.0));
mg3d.Positions.Add(new Point3D(-width, -height, 0.0));
mg3d.Positions.Add(new Point3D(width, -height, 0.0));
mg3d.Positions.Add(new Point3D(width, height, 0.0));


double fieldOfViewInRadians = pCamera.FieldOfView * (Math.PI / 180.0);
var z = (width) / Math.Tan(0.5 * fieldOfViewInRadians);
pCamera.Position = new Point3D(0.0, 0.0, z);
Run Code Online (Sandbox Code Playgroud)

如果窗口大小发生变化,您还需要确保重新计算。之后,您可以制作任何您想要的 3D 动画。