OpenGL - 如何在调整大小时适应 window

OpenGL - how to fit a window on resize

我有一个以 window 屏幕为中心的形状。现在 window resize 它保持不变(相同的宽度和高度)。 调整大小时使其适合 window 并保持纵横比的最佳方法是什么?

const int WIDTH = 490;
const int HEIGHT = 600;

/**
* render scene
*/
void renderScene(void)
{
    //clear all data on scene
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //set white bg color
    glClearColor(1, 1, 1, 1);

    glColor3ub(153, 153, 255);
    glBegin(GL_POLYGON);
        glVertex2f(60, 310);
        glVertex2f(245, 50);
        glVertex2f(430, 310);
        glVertex2f(245, 530);
    glEnd();

    glutSwapBuffers();
}

/**
* reshape scene
*/
void reshapeScene(GLint width, GLint height)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glViewport(0, 0, width, height);
    gluOrtho2D(0, width, height, 0);
    glMatrixMode(GL_MODELVIEW);

    glutPostRedisplay();
}

/**
* entry point
*/
int main(int argc, char **argv)
{
    //set window properties
    glutInit(&argc, argv);  

    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
    glutInitWindowSize(WIDTH, HEIGHT);
    glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH)-WIDTH)/2, (glutGet(GLUT_SCREEN_HEIGHT)-HEIGHT)/2);
    glutCreateWindow("Test Window");

    //paste opengl version in console
    printf((const char*)glGetString(GL_VERSION));

    //register callbacks
    glutDisplayFunc(renderScene);
    glutReshapeFunc(reshapeScene);

    //start animation
    glutMainLoop();

    return 0;
}

谢谢

顶部:

const int WIDTH = 490;
const int HEIGHT = 600;
const float ASPECT = float(WIDTH)/HEIGHT;   // desired aspect ratio

然后reshapeScene:

void reshapeScene(GLint width, GLint height)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    int w = height * ASPECT;           // w is width adjusted for aspect ratio
    int left = (width - w) / 2;
    glViewport(left, 0, w, height);       // fix up the viewport to maintain aspect ratio
    gluOrtho2D(0, WIDTH, HEIGHT, 0);   // only the window is changing, not the camera
    glMatrixMode(GL_MODELVIEW);

    glutPostRedisplay();
}

因为您没有将 window 调整大小限制为特定的纵横比,所以您需要选择两个维度之一(这里是高度)来驱动视口重塑并根据它计算调整后的宽度高度和所需的纵横比。请参阅上面调整后的 glViewport 调用。

此外,gluOrtho2D 本质上是您的相机。因为你没有移动相机或物体太多,所以你不需要改变它(所以它只使用初始的 WIDTHHEIGHT)。