有时在业务中需要给一个几何图形的顶点坐标编号,因为只有一个连续的坐标点集合,但是编号需要按照顺时针,如果直接编号可能出现逆时针编号(如果绘制图形是逆时针,那么集合的顺序也是逆时针的),这是就需要反过来编号。
代码
直接上代码吧
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
void Main()
{
//var list = new List<Point> { new Point(0, 0), new Point(1, 0), new Point(1, 1), new Point(0, 1), new Point(0, 0) };
//var list = new List<Point> {
//new Point{ X= 0.0000m , Y= 0.0000m },
//new Point{ X= 0.6910m , Y= -1.4898m },
//new Point{ X= 1.6711m , Y= -0.4859m },
//new Point{ X= 2.8993m , Y= -1.1923m },
//new Point{ X= 3.5112m , Y= -0.1284m },
//new Point{ X= 4.3632m , Y= 0.5923m },
//new Point{ X= 5.5666m , Y= -0.3620m },
//new Point{ X= 4.5989m , Y= -0.8453m },
//new Point{ X= 6.5467m , Y= -0.8453m },
//new Point{ X= 6.5467m , Y= 0.4560m },
//new Point{ X= 4.8347m , Y= 1.2863m },
//new Point{ X= 3.0978m , Y= 1.2615m },
//new Point{ X= 2.4899m , Y= 0.3073m },
//new Point{ X= 0.0000m , Y= 0.0000m },
//};
var list = new List<Point>{
new Point{ X= 1.4665m, Y= -5.3022m},
new Point{ X= 1.8634m, Y= -2.9629m},
new Point{ X= 3.2525m, Y= -4.8858m},
new Point{ X= 4.1852m, Y= -3.1017m},
new Point{ X= 6.1499m, Y= -4.6083m},
new Point{ X= 8.0351m, Y= -3.9343m},
new Point{ X= 7.3207m, Y= -6.1546m},
new Point{ X= 4.6218m, Y= -5.5995m},
new Point{ X= 4.7919m, Y= -4.7727m},
new Point{ X= 6.1987m, Y= -5.0621m},
new Point{ X= 4.9393m, Y= -4.2515m},
new Point{ X= 4.0265m, Y= -4.7669m},
new Point{ X= 4.0265m, Y= -5.8770m},
new Point{ X= 1.4665m, Y= -5.3022m},
};
decimal sum = 0;
for (int i = 0; i < list.Count - 1; i++)
{
sum += (list[i + 1].X - list[i].X) * (list[i + 1].Y + list[i].Y);
}
if (sum > 0)
{
Console.WriteLine("顺时针,sum="+sum);
}
else
{
Console.WriteLine("逆时针,sum="+sum);
}
}
class Point
{
public Point()
{
}
public Point(decimal x, decimal y)
{
X = x;
Y = y;
}
public decimal X { get; set; }
public decimal Y { get; set; }
}
主要逻辑就是计算 sum += (P[n+1].X-Pn.Y)*(P[n+1].X+P[N].Y));
具体原理见参考资料
参考资料
- Determining the Winding of a Polygon Given as a Set of Ordered Points
- How to determine if a list of polygon points are in clockwise order?
本文会经常更新,请阅读原文: https://dashenxian.github.io/post/%E5%88%A4%E6%96%AD%E5%87%A0%E4%BD%95%E5%9B%BE%E5%BD%A2%E9%A1%B6%E7%82%B9%E5%9D%90%E6%A0%87%E9%9B%86%E5%90%88%E6%98%AF%E9%A1%BA%E6%97%B6%E9%92%88%E8%BF%98%E6%98%AF%E9%80%86%E6%97%B6%E9%92%88 ,以避免陈旧错误知识的误导,同时有更好的阅读体验。
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 小神仙 (包含链接: https://dashenxian.github.io ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 (125880321@qq.com) 。