C# GDI+ 绘制等高线图,请给出具体代码
时间: 2024-05-18 20:17:45 浏览: 13
以下是一个简单的使用C# GDI+绘制等高线图的示例代码:
```csharp
private void DrawContourMap(Graphics g, int[,] elevationData, int contourInterval)
{
int width = elevationData.GetLength(0);
int height = elevationData.GetLength(1);
// 计算等高线的数量
int numContours = (int)Math.Ceiling((double)(elevationData.Cast<int>().Max() - elevationData.Cast<int>().Min()) / contourInterval);
// 绘制等高线
for (int contour = 0; contour < numContours; contour++)
{
int elevation = elevationData.Cast<int>().Min() + contour * contourInterval;
// 创建一个路径对象
GraphicsPath path = new GraphicsPath();
// 遍历每个像素,找到高度等于当前等高线高度的像素,并绘制等高线
for (int y = 0; y < height - 1; y++)
{
for (int x = 0; x < width - 1; x++)
{
// 获取当前像素的高度值,并判断是否等于当前等高线高度
int topLeft = elevationData[x, y];
int topRight = elevationData[x + 1, y];
int bottomLeft = elevationData[x, y + 1];
int bottomRight = elevationData[x + 1, y + 1];
if (topLeft == elevation || topRight == elevation || bottomLeft == elevation || bottomRight == elevation)
{
// 将当前像素的四个角落的点添加到路径中
PointF[] points = new PointF[4];
points[0] = new PointF(x, y);
points[1] = new PointF(x + 1, y);
points[2] = new PointF(x, y + 1);
points[3] = new PointF(x + 1, y + 1);
path.AddPolygon(points);
}
}
}
// 绘制路径
g.DrawPath(new Pen(Color.Black), path);
}
}
```
其中,`elevationData`是一个二维数组,表示高度数据;`contourInterval`是等高线间隔。该方法会根据高度数据和等高线间隔计算出等高线数量,并遍历每个像素,找到高度等于当前等高线高度的像素,并将其四个角落的点添加到一个路径对象中,最后绘制路径即可。