C++ 调整OpenGL窗口的大小会导致其崩溃

C++ 调整OpenGL窗口的大小会导致其崩溃,c++,opengl,graphics,glut,C++,Opengl,Graphics,Glut,由于某种原因,当我调整OpenGL窗口的大小时,一切都会崩溃。图像失真,坐标不起作用,所有东西都会散架。我正准备把它设置好 //Code to setup glut glutInitWindowSize(appWidth, appHeight); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glutCreateWindow("Test Window"); //In drawing function glMatrixMode(GL_MODELVIE

由于某种原因,当我调整OpenGL窗口的大小时,一切都会崩溃。图像失真,坐标不起作用,所有东西都会散架。我正准备把它设置好

//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应用程序严格来说是二维的

这是它最初的样子:


调整大小后是这样的:

您不应该忘记挂接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);
}

用C++来替换C风格的铸件,因为你正在使用C++:)图像不再可用。