调整OpenGL窗口的大小会导致它崩溃

时间:2009-03-15 21:52:37

标签: c++ opengl graphics glut

出于某种原因,当我调整OpenGL窗口大小时,一切都崩溃了。图像失真,坐标不起作用,一切都崩溃了。我正在唱Glut来设置它。

//Code to setup glut
glutInitWindowSize(appWidth, appHeight);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutCreateWindow("Test Window");

//In drawing function
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);

//Resize function
void resize(int w, int h)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, w, h, 0);
}

OpenGL应用程序严格来说是2D。

这是最初的样子:http://www.picgarage.net/images/Corre_53880_651.jpeg

这是调整大小后的样子:http://www.picgarage.net/images/wrong_53885_268.jpeg

1 个答案:

答案 0 :(得分:17)

你不应该忘记勾住GLUT'重塑'事件:

glutReshapeFunc(resize);

重置视口:

void resize(int w, int h)
{
    glViewport(0, 0, width, height); //NEW
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, w, h, 0);
}

透视投影必须考虑新的宽高比:

void resizeWindow(int width, int height)
{
    double asratio;

    if (height == 0) height = 1; //to avoid divide-by-zero

    asratio = width / (double) height;

    glViewport(0, 0, width, height); //adjust GL viewport

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(FOV, asratio, ZMIN, ZMAX); //adjust perspective
    glMatrixMode(GL_MODELVIEW);
}