opengl 使用glutReshapeFunc更改窗口大小时显示错误

rbl8hiat  于 2022-11-04  发布在  其他
关注(0)|答案(1)|浏览(179)

我已经知道glutReshapeFunc可以用来响应窗口大小调整,所以我用它来重置投影矩阵和渲染形状以匹配窗口。代码如下:


# include <GLUT/glut.h>

GLsizei wndWidth = 400;
GLsizei wndHeight = 300;

void init() {
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, 400, 0, 300);
}

void drawSegment() {
    glClear(GL_COLOR_BUFFER_BIT);

    glColor3f(0, 0, 1.0);

    glBegin(GL_LINE_LOOP);
    glVertex2i(10, 10);
    glVertex2i(wndWidth-10, wndHeight-10);
    glVertex2i(wndWidth-10, 10);
    glEnd();

    glFlush();
}

void reshapeFunc(int width, int height) {

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, GLdouble(width), 0, GLdouble(height));

    glClear(GL_COLOR_BUFFER_BIT);

    wndWidth = width;
    wndHeight = height;
}

int main(int argc, char**argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);

    glutInitWindowSize(400, 300);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Draw Window");

    init();
    glutDisplayFunc(drawSegment);
    glutReshapeFunc(reshapeFunc);

    glutMainLoop();
}

在我看来,窗口调整大小后,三角形应该总是占据窗口的一半。但事实上,三角形在窗口调整大小后仍然保持其大小,就好像wndWidthwndHeightdrawSegment中没有变化一样。那么为什么我会得到错误的结果,我该如何修正呢?

pqwbnv8z

pqwbnv8z1#

投影矩阵将视图坐标变换为剪辑坐标,并且剪辑坐标被变换为归一化的设备坐标(在正投影处,剪辑坐标和归一化的设备坐标相等)。
标准化设备坐标如何Map到窗口坐标由glViewport指定。
更改窗口大小后,必须重新指定Map:

void reshapeFunc(int width, int height) {

    glViewport(0, 0, width, height);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, GLdouble(width), 0, GLdouble(height));

    wndWidth = width;
    wndHeight = height;
}

相关问题