我主要是把它扔在那里,因为这个问题引起了我的兴趣,这是我没有专业知识的东西,我想引起讨论。
我采用了Point in Polygon 伪代码并试图使其适合您的情况。您似乎只对确定某些东西是顺时针还是逆时针缠绕感兴趣。这是一个简单的测试和一个非常简单(粗略)的 C# 实现。
[Test]
public void Test_DetermineWindingDirection()
{
GraphicsPath path = new GraphicsPath();
// Set up points collection
PointF[] pts = new[] {new PointF(10, 60),
new PointF(50, 110),
new PointF(90, 60)};
path.AddLines(pts);
foreach(var point in path.PathPoints)
{
Console.WriteLine("X: {0}, Y: {1}",point.X, point.Y);
}
WindingDirection windingVal = DetermineWindingDirection(path.PathPoints);
Console.WriteLine("Winding value: {0}", windingVal);
Assert.AreEqual(WindingDirection.Clockwise, windingVal);
path.Reverse();
foreach(var point in path.PathPoints)
{
Console.WriteLine("X: {0}, Y: {1}",point.X, point.Y);
}
windingVal = DetermineWindingDirection(path.PathPoints);
Console.WriteLine("Winding value: {0}", windingVal);
Assert.AreEqual(WindingDirection.CounterClockWise, windingVal);
}
public enum WindingDirection
{
Clockwise,
CounterClockWise
}
public static WindingDirection DetermineWindingDirection(PointF[] polygon)
{
// find a point in the middle
float middleX = polygon.Average(p => p.X);
float middleY = polygon.Average(p => p.Y);
var pointInPolygon = new PointF(middleX, middleY);
Console.WriteLine("MiddlePoint = {0}", pointInPolygon);
double w = 0;
var points = polygon.Select(point =>
{
var newPoint = new PointF(point.X - pointInPolygon.X, point.Y - pointInPolygon.Y);
Console.WriteLine("New Point: {0}", newPoint);
return newPoint;
}).ToList();
for (int i = 0; i < points.Count; i++)
{
var secondPoint = i + 1 == points.Count ? 0 : i + 1;
double X = points[i].X;
double Xp1 = points[secondPoint].X;
double Y = points[i].Y;
double Yp1 = points[secondPoint].Y;
if (Y * Yp1 < 0)
{
double r = X + ((Y * (Xp1 - X)) / (Y - Yp1));
if (r > 0)
if (Y < 0)
w = w + 1;
else
w = w - 1;
}
else if ((Y == 0) && (X > 0))
{
if (Yp1 > 0)
w = w + .5;
else
w = w - .5;
}
else if ((Yp1 == 0) && (Xp1 > 0))
{
if (Y < 0)
w = w + .5;
else
w = w - .5;
}
}
return w > 0 ? WindingDirection.ClockWise : WindingDirection.CounterClockwise;
}
我提出的不同之处在于,这对您的问题有点特殊,因为我已经计算了所有点的 X 和 Y 的平均值,并将其用作“多边形中的点”值。所以,只传递一个点数组,它会在它们中间找到一些东西。
我还假设 V i+1 在到达点数组的边界时应该环绕,这样
if (i + 1 == points.Count)
// use points[0] instead
这尚未优化,它只是可能回答您的问题。也许你自己已经想出了这个。
希望有建设性的批评。:)