在WPF中,我們可以使用VisualTreeHelper.GetDescendantBounds(Viewport3D)
輕鬆獲取ModelVisual3D的可見2D內容邊界而無需轉換。但是,當ModelVisual3D發生變形時,GetDescendantBounds
會返回比可見內容更大的邊界。我如何獲得可見內容的準確界限?WPF中的可見2D內容邊界ModelVisual3D
代碼XAML:
<Grid Background="LightGray">
<Viewport3D x:Name="MyViewport">
<Viewport3D.Camera>
<OrthographicCamera Position="3 3 5" LookDirection="-3 -3 -5" Width="3"/>
</Viewport3D.Camera>
<Viewport3D.Children>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight Color="White" Direction="-1 -1 -1"/>
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D x:Name="MyVisual">
<ModelVisual3D.Content>
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="0,0,0 1,0,0 0,1,0 1,1,0 0,0,1 1,0,1 0,1,1 1,1,1"
TriangleIndices="0,2,1 1,2,3 0,4,2 2,4,6 0,1,4 1,5,4 1,7,5 1,3,7 4,5,6 7,6,5 2,6,3 3,6,7"/>
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Red"/>
</GeometryModel3D.Material>
<!--<GeometryModel3D.Transform>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D Axis="1 1 0" Angle="5"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
</GeometryModel3D.Transform>-->
</GeometryModel3D>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D.Children>
</Viewport3D>
<Rectangle x:Name="MyRegion" Stroke="Blue" StrokeThickness="1" VerticalAlignment="Top" HorizontalAlignment="Left"/>
</Grid>
代碼behing:
var bounds = VisualTreeHelper.GetDescendantBounds(MyViewport);
MyRegion.Width = bounds.Width;
MyRegion.Height = bounds.Height;
MyRegion.Margin = new Thickness(bounds.Left, bounds.Top, 0, 0);
請注意,我使用了「多邊形」來顯示屏幕上的線條,以顯示我如何完成您的問題。如果您只想顯示外部邊界,則不需要使用它。順便說一下,所有的點都在「Rect」中三次結合。 – walterlv
thx。它工作得非常好。我只是改進你的方法來滿足更復雜的層次結構。 – Iron