可直接复制使用
#include <iostream>
#include <vector>
#include <math.h>
typedef struct point{
double x;
double y;
}Point;
/**
*@brief 多边形等距放大缩小(支持凹多边形)
*@param polygon 需要放大的多边形坐标列表
*@param distance 放大的距离(正数放大,负数缩小)
*@return 放大的多边形坐标列表
*/
std::vector<Point> calcPolygonExtra(std::vector<Point> polygon,double distance){
auto norm = [](double x,double y){
return sqrt((x * x) + (y * y));
};
std::vector<Point> newPolygon;
int len = polygon.size();
for(int i = 0 ; i < len ; i++){
Point point = polygon[i];
Point point1 = polygon[i == 0 ? len - 1 : i - 1];
Point point2 = polygon[i == len - 1 ? 0 : i + 1];
double vectorX1 = point1.x - point.x;
double vectorY1 = point1.y - point.y;
double n1 = norm(vectorX1,vectorY1);
double vectorUnitX1 = vectorX1/n1;
double vectorUnitY1 = vectorY1/n1;
double vectorX2 = point2.x - point.x;
double vectorY2 = point2.y - point.y;
double n2 = norm(vectorX2,vectorY2);
double vectorUnitX2 = vectorX2/n2;
double vectorUnitY2 = vectorY2/n2;
double vectorLen = -distance / sqrt((1 - ((vectorUnitX1 * vectorUnitX2) + (vectorUnitY1 * vectorUnitY2))) / 2);
// 根据向量的叉乘积来判断角是凹角还是凸角
if (((vectorX1 * vectorY2) + (-1 * vectorY1 * vectorX2)) < 0) {
vectorUnitX2 *= -1;
vectorUnitY2 *= -1;
vectorUnitX1 *= -1;
vectorUnitY1 *= -1;
}
double vectorX = vectorUnitX1 + vectorUnitX2;
double vectorY = vectorUnitY1 + vectorUnitY2;
double n = vectorLen / norm(vectorX, vectorY);
double vectorUnitX = vectorX * n;
double vectorUnitY = vectorY * n;
Point newPos;
newPos.x = vectorUnitX + point.x;
newPos.y = vectorUnitY + point.y;
newPolygon.push_back(newPos);
}
return newPolygon;
}
int main()
{
return 0;
}