开发了一个模块,可用来计算平面一些点所构成的凸包。模块名为ConvexHull.dll。
使用方法是这样的,新建一个WinForm工程(控制台工程也行,只是输出结果不大直观),引用ConvexHull.dll,然后在Form1代码中引用模块的命名空间:
using Hiquotion.ComputingGeometry;
模块中包含一个类ConvexHull,用这个类声明一个对象,然后用平面点的集合类(Points)实例化:
实例化
private ConvexHull ch;
private Points p = new Points();
p.Add(new CGPoint(10, 10));
p.Add(new CGPoint(30, 50));
p.Add(new CGPoint(10, 30));
p.Add(new CGPoint(20, 70));
p.Add(new CGPoint(30, 20));
p.Add(new CGPoint(50, 20));
p.Add(new CGPoint(50, 30));
p.Add(new CGPoint(20, 55));
p.Add(new CGPoint(60, 10));
ch = new ConvexHull(p);
private Points p = new Points();
p.Add(new CGPoint(10, 10));
p.Add(new CGPoint(30, 50));
p.Add(new CGPoint(10, 30));
p.Add(new CGPoint(20, 70));
p.Add(new CGPoint(30, 20));
p.Add(new CGPoint(50, 20));
p.Add(new CGPoint(50, 30));
p.Add(new CGPoint(20, 55));
p.Add(new CGPoint(60, 10));
ch = new ConvexHull(p);
然后就可以调用ConvexHull的方法GetConvexHull()来获取凸包了。这个方法返回一个Points对象,表示凸包顶点的集合。下面的代码可以获取凸包顶点。
private Points l = new List<CGPoint>();
l = ch.GetConvexHull();
l = ch.GetConvexHull();
为了测试结果是否正确,我们在窗体上绘制点集中所有的点,然后把凸包顶点用闭合的直线段连接起来。绘制的实现是在Form1的OnPaint方法中,可以参考《C#高级编程(第六版)》
测试
private PointF[] pointf;
pointf = new PointF[l.Count];
for (int i = 0; i < l.Count; i++)
{
pointf[i] = new PointF(l[i].X, l[i].Y);
}
Graphics dc = e.Graphics;
Pen redPen = new Pen(Color.Red, 3);
redPen.Brush = new SolidBrush(Color.Red);
foreach (CGPoint pt in p)
{
dc.FillEllipse(redPen.Brush, new RectangleF(pt.X - 2.5F, pt.Y - 2.5F, 5, 5));
}
Pen bluePen = new Pen(Color.Blue, 2);
dc.DrawPolygon(bluePen, pointf);
pointf = new PointF[l.Count];
for (int i = 0; i < l.Count; i++)
{
pointf[i] = new PointF(l[i].X, l[i].Y);
}
Graphics dc = e.Graphics;
Pen redPen = new Pen(Color.Red, 3);
redPen.Brush = new SolidBrush(Color.Red);
foreach (CGPoint pt in p)
{
dc.FillEllipse(redPen.Brush, new RectangleF(pt.X - 2.5F, pt.Y - 2.5F, 5, 5));
}
Pen bluePen = new Pen(Color.Blue, 2);
dc.DrawPolygon(bluePen, pointf);
测试结果如下图所示。