参考:https://zhuanlan.zhihu.com/p/285544731
思路:
(1)将多边形分为很多个三角形计算
(2)已知三个顶点计算两条边向量
(3)利用向量叉积的几何意义(两个向量的叉积为这两个向量组成的平行四边形的面积)计算三角形面积
(4)这样计算得到的面积是有向面积(有正有负),故可以用于计算凹多边形的面积。
#include <iostream>
#include <vector>
using namespace std;
//已知三角形三个顶点坐标,计算三角形面积(这个面积是有向的:有正有负,故可以用来计算凹多边形的面积)
float CalculateTriangle(vector<pair<int, int>> vertex)
{
//计算两个边对应的向量
int v12_x = vertex[1].first - vertex[0].first;
int v12_y = vertex[1].second - vertex[0].second;
int v13_x = vertex[2].first - vertex[0].first;
int v13_y = vertex[2].second - vertex[0].second;
return(v12_x * v13_y - v12_y * v13_x) / 2.0; //利用向量叉积计算
}
//已知多边形各个顶点,计算多边形的面积
float CalculatePolygon(vector<pair<int, int>> vertex_polygon)
{
float areas = 0.0;
for (int i = 1; i < vertex_polygon.size() - 1; i++)
{
vector<pair<int, int>> vertex;
vertex.push_back(vertex_polygon[0]);
vertex.push_back(vertex_polygon[i]);
vertex.push_back(vertex_polygon[i + 1]);
areas += CalculateTriangle(vertex);
}
return areas;
}
int main(int argc, char** argv)
{
//构造一个三角形的三个顶点(顺时针)
vector<pair<int, int>> vertex;
vertex.push_back(make_pair(1, 0));
vertex.push_back(make_pair(3, 0));
vertex.push_back(make_pair(2, 3));
cout << CalculateTriangle(vertex) << endl;
//计算多边形
vector<pair<int, int>> vertex_polygon;
vertex_polygon.push_back(make_pair(0, 0));
vertex_polygon.push_back(make_pair(1, 0));
vertex_polygon.push_back(make_pair(1, 1));
vertex_polygon.push_back(make_pair(0, 1));
cout << CalculatePolygon(vertex_polygon) << endl;
//一个凹的六边形
vector<pair<int, int>> vertex_polygon_six;
vertex_polygon_six.push_back(make_pair(1, 1));
vertex_polygon_six.push_back(make_pair(4, 1));
vertex_polygon_six.push_back(make_pair(3, 2));
vertex_polygon_six.push_back(make_pair(4, 3));
vertex_polygon_six.push_back(make_pair(1, 3));
vertex_polygon_six.push_back(make_pair(2, 2));
cout << CalculatePolygon(vertex_polygon_six) << endl;
return 0;
}