C#编程之3D平移布局
这里我们主要讲一下3D图形以三维面平移的设计方法。
3D图按照三维平移,可以有上,下,左,右,前,后 ,共6个方向,我们分别将这六个操作由按键来实现操作。
对于按键的布局我们上下为一列,左右前后为一行。
1 <DockPanel.Resources> 2 <Style TargetType="Button"> 3 <Setter Property="HorizontalAlignment" Value="Center"/> 4 <Setter Property="Padding" Value="3"/> 5 </Style> 6 </DockPanel.Resources> 7 8 <StackPanel DockPanel.Dock="Top" Background="Gray" Height="auto"> 9 <Button Click="up_Click">↑</Button> 10 <Button Click="down_Click">↓</Button> 11 <StackPanel HorizontalAlignment="Center" 12 Orientation="Horizontal"> 13 <Button Click="left_Click">←</Button> 14 <Button Click="right_Click">→</Button> 15 <Button Click="out_Click">↖</Button> 16 <Button Click="in_Click">↘</Button> 17 </StackPanel> 18 </StackPanel>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private void up_Click(object sender, RoutedEventArgs e) { transform.OffsetY++; } private void left_Click(object sender, RoutedEventArgs e) { transform.OffsetX--; } private void out_Click(object sender, RoutedEventArgs e) { transform.OffsetZ--; } private void in_Click(object sender, RoutedEventArgs e) { transform.OffsetZ++; } private void right_Click(object sender, RoutedEventArgs e) { transform.OffsetX++; } private void down_Click(object sender, RoutedEventArgs e) { transform.OffsetY—; }
首先定义按键样式原模板,接着按键叠加方式有上至下,背景为灰色,高度自动调整,在放置上下按键后,创建由中心开始的横向排列按键,同时为所有的按键添加按键点击事件处理函数,效果:
接着,创建一个三维图形:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<Viewport3D Width="600" Margin="0,0,0,0"> <Viewport3D.Camera> <PerspectiveCamera Position="-2.5 2.5 5" LookDirection="0.5 -0.5 -1"/> </Viewport3D.Camera> <ModelVisual3D> <ModelVisual3D.Content> <Model3DGroup> <DirectionalLight Direction="1 0 -7" Color="White"/> <GeometryModel3D> <GeometryModel3D.Geometry> <MeshGeometry3D Positions="-1 1 1, 1 1 1, -1 -1 1, 1 -1 1, -1 1 -1, 1 1 -1, -1 -1 -1, 1 -1 -1 1 1 1, 1 1 -1, 1 -1 1, 1 -1 -1, -1 1 1, -1 1 -1, -1 -1 1, -1 -1 -1 -1 1 1, -1 1 -1, 1 1 1, 1 1 -1, -1 -1 1, -1 -1 -1, 1 -1 1, 1 -1 -1" TriangleIndices="0 2 1, 1 2 3, 5 6 4, 5 7 6 8 10 9, 9 10 11, 13 14 12, 13 15 14 16 18 17, 17 18 19, 22 21 20, 22 23 21"/> </GeometryModel3D.Geometry> <GeometryModel3D.Material> <DiffuseMaterial Brush="Green"/> </GeometryModel3D.Material> <GeometryModel3D.BackMaterial> <DiffuseMaterial Brush="Red"/> </GeometryModel3D.BackMaterial> </GeometryModel3D> </Model3DGroup> </ModelVisual3D.Content> <ModelVisual3D.Transform> <TranslateTransform3D x:Name="transform" /> </ModelVisual3D.Transform> </ModelVisual3D> </Viewport3D>
首先是创建一个三维可视区: <Viewport3D Width="600" Margin="0,0,0,0">
调整相机位置与方向
<Viewport3D.Camera> <PerspectiveCamera Position="-2.5,2.5,5" LookDirection="0.5,-0.5,1"/> </Viewport3D.Camera>