多边形面积求解的方法很多,其中比较多见的就是增加一个点P,然后分别连接多边形各个定点与P点,然后计算每个三角形的符号面积(面积有正负之分),求和就可以计算出面积。
鉴于上面的方法,我们也可以用另外一种更简单的方法,将P点直接放在V0点,那么我们要求的面积就是V0V1V2,VoV2V3,...,V0Vn-2Vn-3的面积和。此处注意,如果我们假设逆时针的三角形(如上图V0V2V3)为正,那么顺时针的面积(如上图V0V1V2)就为负。
下面的代码实现部分:
代码
1
private
double
GetAreaOfPolyGon(List
<
Point
>
points)
2 {
3 double area = 0 ;
4 if (points.Count < 3 )
5 {
6 throw new Exception( " 至少需要3个点才有面积 " );
7 }
8
9 Point p1 = points[ 0 ];
10 for ( int i = 1 ; i < points.Count - 1 ; i ++ )
11 {
12 Point p2 = points[i];
13 Point p3 = points[i + 1 ];
14 // 构造向量
15 Point vecP1P2 = new Point(p2.X - p1.X, p2.Y - p1.Y);
16 Point vecP2P3 = new Point(p3.X - p2.X, p3.Y - p2.Y);
17 double vecMult = vecP1P2.X * vecP2P3.Y - vecP1P2.Y * vecP2P3.X; // 用于判断顺时针还是逆时针
18 int sign = 0 ;
19 if (vecMult > 0 )
20 {
21 sign = 1 ;
22 }
23 else if (vecMult < 0 )
24 {
25 sign = - 1 ;
26 }
27 double triArea = GetAreaOfTriangle(p1, p2, p3) * sign;
28 area += triArea;
29 }
30 return Math.Abs(area);
31 }
32
33 private double GetAreaOfTriangle(Point p1, Point p2, Point p3)
34 {
35 double area = 0 ;
36 double p1p2 = GetLineLength(p1, p2);
37 double p2p3 = GetLineLength(p2,p3);
38 double p3p1 = GetLineLength(p3, p1);
39 double s = (p1p2 + p2p3 + p3p1) / 2 ;
40 area = s * (s - p1p2) * (s - p2p3) * (s - p3p1);
41 area = Math.Sqrt(area);
42 return area;
43 }
44
45 private double GetLineLength(Point p1, Point p2)
46 {
47 double length;
48 length = Convert.ToDouble((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y));
49 length = Math.Sqrt(length);
50 return length;
51 }
2 {
3 double area = 0 ;
4 if (points.Count < 3 )
5 {
6 throw new Exception( " 至少需要3个点才有面积 " );
7 }
8
9 Point p1 = points[ 0 ];
10 for ( int i = 1 ; i < points.Count - 1 ; i ++ )
11 {
12 Point p2 = points[i];
13 Point p3 = points[i + 1 ];
14 // 构造向量
15 Point vecP1P2 = new Point(p2.X - p1.X, p2.Y - p1.Y);
16 Point vecP2P3 = new Point(p3.X - p2.X, p3.Y - p2.Y);
17 double vecMult = vecP1P2.X * vecP2P3.Y - vecP1P2.Y * vecP2P3.X; // 用于判断顺时针还是逆时针
18 int sign = 0 ;
19 if (vecMult > 0 )
20 {
21 sign = 1 ;
22 }
23 else if (vecMult < 0 )
24 {
25 sign = - 1 ;
26 }
27 double triArea = GetAreaOfTriangle(p1, p2, p3) * sign;
28 area += triArea;
29 }
30 return Math.Abs(area);
31 }
32
33 private double GetAreaOfTriangle(Point p1, Point p2, Point p3)
34 {
35 double area = 0 ;
36 double p1p2 = GetLineLength(p1, p2);
37 double p2p3 = GetLineLength(p2,p3);
38 double p3p1 = GetLineLength(p3, p1);
39 double s = (p1p2 + p2p3 + p3p1) / 2 ;
40 area = s * (s - p1p2) * (s - p2p3) * (s - p3p1);
41 area = Math.Sqrt(area);
42 return area;
43 }
44
45 private double GetLineLength(Point p1, Point p2)
46 {
47 double length;
48 length = Convert.ToDouble((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y));
49 length = Math.Sqrt(length);
50 return length;
51 }