通过旋转、平移求取矩形顶点坐标

前言

旋转和平移是几何变换中两个基本的操作,它们可以用来改变图形的位置和方向

一、旋转

旋转是指将图形绕某一点(通常是原点或中心点)旋转一定的角度。旋转会改变图形的方向,但不会改变其形状或大小。

在二维空间中,旋转变换可以用旋转矩阵表示。假设我们要绕原点 (0, 0) 旋转一个角度 θ,旋转矩阵为:

旋转公式: 对于一个点 (x,y)(x, y)(x,y),旋转后得到的新坐标 (x′,y′)(x', y')(x′,y′) 可以用以下公式计算: 

// 计算旋转后的坐标
Point rotatePoint(const Point& p, float theta) {
    float cosTheta = std::cos(theta);
    float sinTheta = std::sin(theta);

    float xNew = p.x * cosTheta - p.y * sinTheta;
    float yNew = p.x * sinTheta + p.y * cosTheta;

    return {xNew, yNew};
}

二、平移 

平移是指将图形在平面上移动一定的距离。平移不会改变图形的方向、大小或形状,只是改变它的位置。

对于一个点 (x,y)(x, y)(x,y),平移 (dx,dy)(dx, dy)(dx,dy) 后的新坐标 (x′,y′)(x', y')(x′,y′) 可以用以下公式计算:

    // 平移到实际坐标系统中
    vertices[0] = {rotatedTopLeft.x + center.x, rotatedTopLeft.y + center.y};
    vertices[1] = {rotatedTopRight.x + center.x, rotatedTopRight.y + center.y};
    vertices[2] = {rotatedBottomRight.x + center.x, rotatedBottomRight.y + center.y};
    vertices[3] = {rotatedBottomLeft.x + center.x, rotatedBottomLeft.y + center.y};

三、已知矩形中心坐标求取矩形顶点坐标

1. 确定矩形相对于中心点的顶点坐标

在未旋转的情况下,矩形的四个顶点相对于中心点的位置为:

2. 应用旋转矩阵得到新的旋转坐标

3. 平移得到实际坐标 

4. 测试代码 

#include <iostream>
#include <cmath>

struct Point {
    float x, y;
};

// 计算旋转后的坐标
Point rotatePoint(const Point& p, const Point& center, float theta) {
    float cosTheta = std::cos(theta);
    float sinTheta = std::sin(theta);

    float xNew = center.x + (p.x * cosTheta - p.y * sinTheta);
    float yNew = center.y + (p.x * sinTheta + p.y * cosTheta);

    return {xNew, yNew};
}

// 计算矩形的四个顶点
void calculateRectangleVertices(const Point& knownPoint, float width, float height, float angle, Point* vertices) {
    // 矩形顶点相对于已知点(左上角)的未旋转坐标
    Point topLeft = {0, 0};  // 已知点
    Point topRight = {width, 0};
    Point bottomRight = {width, -height};
    Point bottomLeft = {0, -height};

    // 旋转每个顶点并加上已知点坐标
    vertices[0] = rotatePoint(topLeft, knownPoint, angle);
    vertices[1] = rotatePoint(topRight, knownPoint, angle);
    vertices[2] = rotatePoint(bottomRight, knownPoint, angle);
    vertices[3] = rotatePoint(bottomLeft, knownPoint, angle);
}

int main() {
    // 示例:已知点 (3, 4) 是矩形的左上角,宽 4,高 2,旋转角度 45 度 (π/4 弧度)
    Point knownPoint = {3, 4};
    float width = 4, height = 2, angle = M_PI / 4;

    Point vertices[4];  // 用于存储四个顶点的坐标
    calculateRectangleVertices(knownPoint, width, height, angle, vertices);

    // 输出矩形的四个顶点坐标
    for (int i = 0; i < 4; ++i) {
        std::cout << "Vertex " << i + 1 << ": (" << vertices[i].x << ", " << vertices[i].y << ")" << std::endl;
    }

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值