此示例展示了如何使用 C# 代碼和 XAML 繪制覆蓋有網格的 3D 表面。示例使用 WPF 和 C# 將紋理應用于三角形展示了如何將紋理應用于三角形。此示例只是使用該技術將包含大網格的位圖應用于表面。
在類級別,程序使用以下代碼來定義將點的 X 和 Z 坐標映射到 0.0 - 1.0 范圍的比例因子。
private const double texture_xscale = (xmax - xmin);
private const double texture_zscale = (zmax - zmin);
下面的代碼顯示了程序如何向 3D 模型添加新點。
// A dictionary to hold points for fast lookup.
private Dictionary<Point3D, int> PointDictionary =new Dictionary<Point3D, int>();// If the point already exists, return its index.
// Otherwise create the point and return its new index.
private int AddPoint(Point3DCollection points,PointCollection texture_coords, Point3D point)
{// If the point is in the point dictionary,// return its saved index.if (PointDictionary.ContainsKey(point))return PointDictionary[point];// We didn't find the point. Create it.points.Add(point);PointDictionary.Add(point, points.Count - 1);// Set the point's texture coordinates.texture_coords.Add(new Point((point.X - xmin) * texture_xscale,(point.Z - zmin) * texture_zscale));// Return the new point's index.return points.Count - 1;
}
與前面的示例一樣,代碼定義了一個字典來保存Point,以便可以快速查找它們。AddPoint方法查找一個點,如果該點尚不存在,則添加它。然后,它使用該點的 X 和 Z 坐標將該點映射到對象紋理使用的 UV 坐標的 0.0 - 1.0 范圍。換句話說,具有最小 X/Z 坐標的點被映射到 (0, 0) 附近的 U/V 坐標,具有最大 X/Z 坐標的點被映射到 (1, 1) 附近的 U/V 坐標。
創建三角形后,程序使用以下代碼來創建其材質。
// Make the surface's material using an image brush.
ImageBrush grid_brush = new ImageBrush();
grid_brush.ImageSource =new BitmapImage(new Uri("Grid.png", UriKind.Relative));
DiffuseMaterial grid_material = new DiffuseMaterial(grid_brush);
文件 Grid.png 僅包含一個 513×513 像素的網格。或者,您也可以在代碼中創建網格。第三種方法是使用偏導數來確定應該在哪里繪制線條,然后使用細長的矩形或框將它們繪制在表面上。(后面的帖子將解釋如何繪制細長的框。)然而,這會需要做更多的工作。
我知道這些例子省略了大量細節。它們相互依存,所以您已經在之前的帖子中看到了關鍵點。細節也相當長,所以為了節省空間,我不會在每篇文章中都包含它們。 |