背景:wpf本身有提供3D的绘制,但是自己通过代码描绘出3D是比较困难的。3D库helix-toolkit支持调用第三方生成的模型,比如Blender这些,所以在wpf上使用3D就变得非常简单。这里是一个通过helix-toolkit库调用第三方生成的3d模型的样例:
1、安装NuGet包:HelixToolkit.Wpf
2、xaml界面中设置相机和光源等参数
引入helix-toolkit命名空间:xmlns:ht="http://helix-toolkit.org/wpf"
XML
<ht:HelixViewport3D
Name="viewport"
DefaultCamera="{Binding ElementName=viewport, Path=Camera}"
MouseDown="Viewport_MouseDown"
ShowCoordinateSystem="True">
<ht:HelixViewport3D.Camera>
<PerspectiveCamera
FieldOfView="80"
LookDirection="-100,-100,-100"
Position="100,100,100"
UpDirection="0,0,1">
<!--<PerspectiveCamera.Transform>
<RotateTransform3D CenterX="0" CenterY="0" CenterZ="0">
<RotateTransform3D.Rotation>
<AxisAngleRotation3D Axis="0,0,1" Angle="0"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
</PerspectiveCamera.Transform>-->
</PerspectiveCamera>
</ht:HelixViewport3D.Camera>
<ht:HelixViewport3D.RotateGesture>
<MouseGesture MouseAction="LeftClick" />
</ht:HelixViewport3D.RotateGesture>
<ht:HelixViewport3D.PanGesture>
<MouseGesture MouseAction="RightClick" />
</ht:HelixViewport3D.PanGesture>
<!-- 光源 -->
<ModelVisual3D>
<ModelVisual3D.Content>
<Model3DGroup>
<!-- 环境光:提亮整体的环境亮度 -->
<AmbientLight Color="#999" />
<!-- 点光源:光影层次感 -->
<PointLight Position="100,0,100" Color="#DDD" />
</Model3DGroup>
</ModelVisual3D.Content>
</ModelVisual3D>
</ht:HelixViewport3D>
3、Code_behind设置点开页面就选择3d模型
cs
public partial class My3D : UserControl
{
public My3D()
{
InitializeComponent();
// 加载外部3D模型文件
Model3DGroup modelGroup = null;
var openFileDialog = new Microsoft.Win32.OpenFileDialog()
{
Filter = "3D模型文件 (*.obj, *.stl, *.ply)|*.obj;*.stl;*.ply"
};
if (openFileDialog.ShowDialog() == true)
{
var importer = new ModelImporter();
modelGroup = importer.Load(openFileDialog.FileName);
}
// 将加载的模型添加到Viewport3D中
if (modelGroup != null)
{
var modelVisual = new ModelVisual3D();
modelVisual.Content = modelGroup;
viewport.Children.Add(modelVisual);
}
}
private void Viewport_MouseDown(object sender, MouseButtonEventArgs e)
{
Point mousePos = e.GetPosition(viewport);
// 执行拾取操作
HitTestResult hitTestResult = VisualTreeHelper.HitTest(viewport, mousePos);
if (hitTestResult != null && hitTestResult.VisualHit is ModelVisual3D)
{
// 获取点击到的ModelVisual3D对象
ModelVisual3D clickedVisual = (ModelVisual3D)hitTestResult.VisualHit;
// 进一步处理点击到的物体
// 例如,获取其名称、执行相应的操作等
MessageBox.Show("点击到了物体");
}
else
{
MessageBox.Show("没有点击到什么啊");
}
}
}
--方法Viewport_MouseDown中判断有没有点击中了我们自己导入的模型