当前位置: 首页 > news >正文

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

前言

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

一、旋转

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

在二维空间中,旋转变换可以用旋转矩阵表示。假设我们要绕原点 (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;
}


http://www.mrgr.cn/news/17864.html

相关文章:

  • 登山第二梯:ROS+VSCode+C++环境配置
  • 编程要由 “手动挡” 变 “自动挡” 了?Cursor+Claude-3.5-Sonnet,Karpathy 点赞的 AI 代码神器。如何使用详细教程
  • osi 7层网络模型
  • 量化交易思维,股票被套,回本应该马上抛掉吗
  • 键盘接入Linux
  • css实现卡片右上角的状态
  • 学习大数据DAY49 考后练习题
  • springboot图书商城
  • PyTorch 2.0常用函数解析与用法
  • 企业IT服务管理(ITSM)的实践与探索
  • 实战项目:俄罗斯方块(四)
  • 个人旅游网(3)——功能详解——旅游路线功能
  • 深入掌握Kubernetes核心:YAML配置详解与实战
  • SQL注入
  • cache flush和cache invalid区别
  • 使用requests做爬虫
  • Python绘制嫦娥奔月
  • Goolge earth studio 高阶2——缓动简单应用
  • 【SQL】Delete使用
  • 【达梦数据库】DBeaver连接达梦数据库