我是 WPF 3D 的新手,所以我可能只是遗漏了一些明显的东西,但是我如何从 3D 转换为 2D 以及(对于给定的 z 位置)从 2D 转换为 3D?
具体来说,我需要两种转换方法:
Point3DToPoint - 如果我在 3D 世界中有一个 (x, y, z) 坐标,我如何确定投影 2D 表面上的 (x, y) 坐标。方法签名:public Point Point3DToPoint(Point3D point3D)
PointAndZToPoint3D -如果我有一个(X,Y)坐标投影2D表面和3D世界中的位置AZ,我怎么确定(X,Y,Z)坐标在3D世界?方法签名:public Point3D PointAndZToPoint3D(Point point, double z)
我希望2D 坐标是从3D 世界的左上角测量的位置Viewport3D
,3D 坐标是相对于 3D 世界的原点 (0, 0, 0) 的位置。
注 1:我发现了这个相关问题,但它只解决了从 3D 到 2D 的转换(而不是相反),我不确定答案是否是最新的。
注 2:我目前使用 .NET 3.5,但如果 .NET 4.0 中的改进对我有帮助,请告诉我。
查尔斯Petzold的3D库,它可以下载这里的“The Petzold.Media3D库”,包含一个类ViewportInfo
与这两个静态方法:
public static Point Point3DToPoint2D(Viewport3D viewport, Point3d point)
public static bool Point2DToPoint3D(Viewport3D viewport, Point, ptIn, out LineRange range)
Point2DToPoint3D
不是精确匹配 forPointAndZToPoint3D()
因为它返回(通过out
参数)aLineRange
而不是特定点,但恰好LineRange
有一个方法PointFromZ(double zValue)
,它提供光线与 z = 定义的平面相交的点zValue
。
代码示例:
using System.Windows;
using System.Windows.Input;
using Petzold.Media3D;
namespace _3DTester
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
/* This MouseDown event handler prints:
(1) the current position of the mouse
(2) the 3D mouse location on the ground plane (z = 0)
(3) the 2D mouse location converted from the 3D location */
private void Window_MouseDown(object sender, MouseEventArgs e)
{
var range = new LineRange();
var isValid = ViewportInfo.Point2DtoPoint3D(Viewport, e.GetPosition(Viewport), out range);
if (!isValid)
MouseLabel.Content = "(no data)";
else
{
var point3D = range.PointFromZ(0);
var point = ViewportInfo.Point3DtoPoint2D(Viewport, point3D);
MouseLabel.Content = e.GetPosition(Viewport) + "\n" + point3D + "\n" + point;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
XAML 代码
<Window
x:Class="_3DTester.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="300"
Width="300"
MouseDown="Window_MouseDown">
<Grid>
<Viewport3D Name="Viewport">
<Viewport3D.Camera>
<PerspectiveCamera
Position="0,0,30"
LookDirection="0,0,-1"
UpDirection="0,1,0" />
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<Model3DGroup>
<DirectionalLight Color="White" Direction="1,-1,-1" />
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D
Positions="0,0,10 -5,-5,0 -5,5,0 5,5,0 5,-5,0"
TriangleIndices="2 1 0 2 0 3 4 3 0 1 4 0" />
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Red" />
</GeometryModel3D.Material>
</GeometryModel3D>
</Model3DGroup>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>
<Label Name="MouseLabel" Content="(no data)" />
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3874 次 |
最近记录: |