C++实现二维坐标系的平移和旋转
有这样一个问题,平面内有一个点集,需要将坐标原点平移,到点集的某一点,然后在将坐标系旋转一定角度使得和点集中地另一个点重合。
坐标变换
坐标变换是空间实体的位置描述,是从一种坐标系统变换到另一种坐标系统的过程。通过建立两个坐标系统之间一一对应关系来实现。是各种比例尺地图测量和编绘中建立地图数学基础必不可少的步骤。两个及以上的坐标转换时由极坐标相对参照确定维数空间。
坐标变换共有五种分别是平移、倍变、旋转、切变、反射,除平移外均以坐标原点为基准点,即变换前后坐标原点不变。
平移:
当把原点 移到 时,平面上任一点 的旧坐标 及其新坐标 之间有下列关系:
其中(1)以新坐标表示旧坐标,(2)以旧坐标表示新坐标,叫做“平移公式”或“移轴公式”。
旋转
如下图, 在2维坐标上,有一点p(x, y) , 直线opの长度为r, 直线op和x轴的正向的夹角为a。 直线op围绕原点做逆时针方向b度的旋转,到达p’ (s,t)
s = r cos(a + b) = r cos(a)cos(b) – r sin(a)sin(b) (1.1)
t = r sin(a + b) = r sin(a)cos(b) + r cos(a) sin(b) (1.2)
其中 x = r cos(a) , y = r sin(a)
代入(1.1), (1.2) ,
s = x cos(b) – y sin(b) (1.3)
t = x sin(b) + y cos(b) (1.4)
代码实现:
#include <iostream>
#include <math.h>
#include<fstream>
#include<cstdlib>
using namespace std;
class Transform {
public:
Transform(int x, double d[]) {
pointNums = x;
if (x<0)
cout << "Not enough" << endl;
int c = 0;
for (int i = 0; i<x; i++) {
for (int j = 0; j<2; j++) {
data[i][j] = d[c];
c++;
}
}
}
void print();
int matPoints();
void translation(int x,double n,double m) ;
void rotation(int x,double ax,double ay);
double data[200][200]; // 点容量
private:
int pointNums; //点的个数
};
//输出点坐标
void Transform::print() {
for (int i = 0; i<pointNums; i++) {
for (int j = 0; j<2; j++) {
cout.width(4);
cout << data[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
//统计点的个数
int Transform::matPoints() {
return pointNums;
}
//二维平移(例如:从p1(x1,y1),平移到p2(x2,y2),n = x2-x1;m=y2-y1)
//输入参数:x为点的个数,n为X轴平移量,m为Y轴平移量。
void Transform::translation(int x,double n,double m) {
for (int i = 0; i<x; i++) {
data[i][0] = data[i][0] + n;
data[i][1] = data[i][1] + m;
}
}
//旋转 将坐标轴的X轴旋转到以原点和某一点的连线上
void Transform::rotation(int x,double ax,double ay) {
double r = sqrt(ax*ax + ay*ay);
double s_a = -ay/r;
double c_a = ax/r;
for (int i = 0; i<x; i++) {
double temp = data[i][0]* c_a - data[i][1]* s_a;
data[i][1] = data[i][0]* s_a + data[i][1]* c_a;
data[i][0] = temp;
}
}
int main(int argc, char** argv) {
double v[100000] = {};
int n;
int cc;
ifstream infile("2.txt",ios::in);
int count =0;
infile>>n;
while(infile){
infile>>cc;
v[count] = cc;
count++;
}
Transform a(n, v);
a.print();
//将坐标原点移到某一点
a.translation(n,-a.data[0][0],-a.data[0][1]);
a.print();
//将x轴旋转,使得x轴与某点重合
double ax = a.data[1][0];
double bx = a.data[1][1];
a.rotation(n,ax,bx);
a.print();
return 0;
}
```cpp
在这里插入代码片
2.txt
10
2 4
6 8
11 14
15 7
22 13
56 7
34 5
13 15
-10 15
10 -19
输出: