平移公式:
x’ = x + tx;
y’ = y + ty;
比例公式:
x’ = x* sx;
y’ = y* sy;
旋转公式:
x’ = x cost - ysint;
y’ = xsint +ycost;(t为弧度)
其实简单来说就是写一个方法依据上述公式,转换图形初始点的坐标,进而进行变换。
代码如下:
很简单的代码,很好理解:
#include <GL/glut.h>
#include <math.h>
typedef float Color[3];
void polygon(double cd[]) {
glBegin(GL_LINE_LOOP);
glLineWidth(10);
for (int i = 0; i < 8; i = i + 2) {
glVertex2f(cd[i], cd[i + 1]);
}
glEnd();
}
double *translation(double cd[], int tx, int ty) {
double *cd_ts;
cd_ts = new double[8];
for (int i = 0; i < 8; i = i + 2) {
cd_ts[i] = cd[i] + tx;
cd_ts[i + 1] = cd[i + 1] + ty;
}
return cd_ts;
}
double *proportion(double cd[], int sx, int sy) {
double *cd_ts;
cd_ts = new double[8];
for (int i = 0; i < 8; i = i + 2) {
cd_ts[i] = cd[i] * sx;
cd_ts[i + 1] = cd[i + 1] * sy;
}
return cd_ts;
}
double *rotate(double cd[], float angle) {
double *cd_ts;
cd_ts = new double[8];
int angle180 = 180;
double Pi = 3.1415926;
float rotate_angle = angle / angle180 * Pi;
for (int i = 0; i < 8; i = i + 2) {
cd_ts[i] = cd[i] * cos(rotate_angle) - cd[i + 1] * sin(rotate_angle);
cd_ts[i + 1] = cd[i] * sin(rotate_angle) + cd[i + 1] * cos(rotate_angle);
}
return cd_ts;
}
void display(void) {
double cd[8] = {100, 100, 100, 200, 200, 200, 200, 100};
Color color = {0.0, 0.0, 0.0};//初始 黑色
Color color1 = {0.0, 1.0, 0.0};//平移 绿色
Color color2 = {1.0, 0.0, 1.0};//比例 紫色
Color color3 = {1.0, 0.0, 0.0};//旋转 红色
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, 500, 500);
glColor3fv(color);//初始图形
polygon(cd);
glColor3fv(color1);//平移
polygon(translation(cd, 50, 50));
glColor3fv(color2);//比例
polygon(proportion(cd, 2, 2));
glColor3fv(color3);//旋转
polygon(rotate(cd, 30));
glFlush();
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RED);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("GraphTransform");
glClearColor(1, 1, 1, 0.0);
glMatrixMode(GL_PROJECTION);//投影模型
gluOrtho2D(0.0, 500.0, 0.0, 500.0);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}