OpenGL - 在窗口大小调整时保持宽高比

时间:2012-04-17 02:37:30

标签: c opengl

我在方形窗口中绘制一个多边形。当我调整窗口大小时,例如通过全屏显示,纵横比会受到干扰。从参考文献中我发现了一种保留纵横比的方法。这是代码:

    void reshape (int width, int height) {
    float cx, halfWidth = width*0.5f;
    float aspect = (float)width/(float)height; 
    glViewport (0, 0, (GLsizei) width, (GLsizei) height);
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    glFrustum(cx-halfWidth*aspect, cx+halfWidth*aspect, bottom, top, zNear, zFar);
    glMatrixMode (GL_MODELVIEW);
}

这里,cx是X中的zNear飞机的眼睛空间中心。我请求有人可以解释我怎么能计算出来。我相信这应该是glFrustum()的前两个参数的平均值。我对吗?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:7)

看起来你想要做的是在宽高比改变时保持视野或视角。有关如何执行此操作的详细信息,请参阅OpenGL常见问题解答的标题为9.085 How can I make a call to glFrustum() that matches my call to gluPerspective()?的部分。这是简短版本:

fov*0.5 = arctan ((top-bottom)*0.5 / near)
top = tan(fov*0.5) * near
bottom = -top
left = aspect * bottom
right = aspect * top

有关详细信息,请参阅链接。

答案 1 :(得分:1)

前两个参数是眼睛空间中左右剪裁平面的X坐标。除非您正在进行离轴技巧(例如,要在多个监视器上显示未中心的投影),否则左右应具有相同的幅度和相反的符号。这将使你的cx变量为零。

如果您在理解glFrustrum时遇到问题,可以使用gluPerspective代替,它有一个简化的界面。