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
<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>
</
<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的屬性進行加減從而達到變換效果。
privatevoid up_Click(object sender, RoutedEventArgs e)
{
transform.OffsetY++;
}
privatevoid left_Click(object sender, RoutedEventArgs e)
{
transform.OffsetX--;
}
privatevoid out_Click(object sender, RoutedEventArgs e)
{
transform.OffsetZ--;
}
privatevoid in_Click(object sender, RoutedEventArgs e)
{
transform.OffsetZ++;
}
privatevoid right_Click(object sender, RoutedEventArgs e)
{
transform.OffsetX++;
}
privatevoid down_Click(object sender, RoutedEventArgs e)
{
transform.OffsetY—;
}