【C++】多边形等距放大缩小,支持凹多边形

可直接复制使用

#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;
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值