glViewport 定义渲染到的(默认)帧缓冲区的区域。
如果你不想渲染到全屏,那么你可以缩小渲染到的区域,glViewport。你可以在边框上放一些黑色条纹。
您的应用程序的纵横比是 winWidth : winHeight
使用glutGet,分别使用参数GLUT_WINDOW_WIDTHGLUT_WINDOW_HEIGHT可以得到当前窗口的大小,可以计算出当前的纵横比:
int currWidth = glutGet( GLUT_WINDOW_WIDTH );
int currHeight = glutGet( GLUT_WINDOW_HEIGHT );
float window_aspcet = (float)currWidth / (float)currHeight;
有了这些信息,视图可以完美地居中于视口:
void display() {
float app_aspcet = (float)winWidth / (float)winHeight;
int currWidth = glutGet( GLUT_WINDOW_WIDTH );
int currHeight = glutGet( GLUT_WINDOW_HEIGHT );
float window_aspcet = (float)currWidth / (float)currHeight;
if ( window_aspcet > app_aspcet )
{
int width = (int)((float)currWidth * app_aspcet / window_aspcet + 0.5f);
glViewport((currWidth - width) / 2, 0, width, currHeight);
}
else
{
int height = (int)((float)currHeight * window_aspcet / app_aspcet + 0.5f);
glViewport(0, (currHeight - height) / 2, currWidth, height);
}
// [...]
}
或者你可以熟练使用正投影的纵横比和中心
void display() {
float app_aspcet = (float)winWidth / (float)winHeight;
int currWidth = glutGet( GLUT_WINDOW_WIDTH );
int currHeight = glutGet( GLUT_WINDOW_HEIGHT );
float window_aspcet = (float)currWidth / (float)currHeight;
glViewport(0, 0, currWidth, currHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if ( window_aspcet > app_aspcet )
{
float delta_width = (float)currWidth * (float)winHeight / (float)currHeight - (float)winWidth;
gluOrtho2D(-delta_width/2.0f, (float)winWidth + delta_width/2.0f, 0.0, (float)winHeight);
}
else
{
float delta_height = (float)currHeight * (float)winWidth / (float)currWidth - (float)winHeight;
gluOrtho2D(0.0, (float)winWidth, -delta_height/2.0f, (float)winHeight + delta_height/2.0f);
}