原文:WPF 3D:使用变换中的TranslateTransform3D
程序效果:
WPF 3D中的TranslateTransform3D应该是所有3D变换中最简单的变换,使用起来非常简单,先定义好3D对象,接着在适当的位置加入变换就可以了。
当然WPF 3D中变换(Transform3D类型)可以应用在如下属性中:
- 照相机:Camera类型
- 3D模型定义:Model3D类型
- 容纳3D模型的Visual3D:ModelVisual3D类型
对于2D的TranslateTransform,只有两个属性X和Y。3D的TranslateTransform则对应OffsetX, OffsetY和OffsetZ属性来调整X,Y,Z三轴的坐标。
下面是界面XAML:
<DockPanel>
<DockPanel.Resources>
<Style TargetType="Button">
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="Padding" Value="3"/>
</Style>
</DockPanel.Resources>
<StackPanel DockPanel.Dock="Top"
Background="Gray">
<Button Click="up_Click">↑</Button>
<StackPanel HorizontalAlignment="Center"
Orientation="Horizontal">
<Button Click="left_Click">←</Button>
<Button Click="out_Click"></Button>
<Button Click="in_Click"></Button>
<Button Click="right_Click">→</Button>
</StackPanel>
<Button Click="down_Click">↓</Button>
</StackPanel>
<Viewport3D>
<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>
</DockPanel>
背后代码则是根据功能,把相应Transform的属性进行加减从而达到变换效果。
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—;
}