opengl 图形变化:平移,比例,旋转

本文介绍了一个使用OpenGL和GLUT库实现的图形变换程序,通过平移、比例缩放及旋转等基本几何变换操作来改变图形的位置、大小和方向。代码示例详细展示了如何通过数学公式计算新的坐标点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

平移公式:

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;

}

效果截图:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值