OpenGL-如何调整窗口大小
OpenGL - how to fit a window on resize
我有一个以窗口屏幕为中心的形状。现在调整窗口大小时,它保持不变(宽度和高度相同)。在调整大小的同时保持其纵横比的最佳方式是什么?
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();
}
因为您没有将窗口的大小限制为特定的纵横比,所以需要从两个维度(此处为高度)中选择一个来驱动视口重塑,并根据该高度和所需的纵横比计算调整后的宽度。参见上文调整后的glViewport
调用。
此外,gluOrtho2D
本质上就是你的相机。由于您没有移动太多相机或对象,因此不需要更改(因此它只使用初始WIDTH
和HEIGHT
)。
相关文章:
- SDL2 调整窗口大小后如何缩放鼠标坐标?
- QGraphics手动调整窗口大小后场景宽度/高度没有变化
- Qt - 防止在拖动标题栏时调整窗口大小
- 在 Direct2D 绘图中,调整窗口大小后尺寸会更改
- 使用第二个线程快速更新 GUI 窗口会通过调整窗口大小或移动窗口而崩溃
- QT调整窗口大小后,删除窗口后
- 在Windows中平滑调整窗口大小(使用Direct2D 1.1)
- 如何使用 WTL 拒绝调整窗口大小
- SDL中的Alpha混合在调整窗口大小后重置
- OpenGL-如何调整窗口大小
- 当在拖动/调整窗口大小的同时对窗口调用isActive()时,返回false.(X11,问题5.4.0)
- 调整窗口大小后交换渲染缓冲区会导致问题
- 避免双击调整窗口大小
- MFC 程序崩溃时调整窗口大小并出现错误"A required resource was not found."
- 调整窗口大小,使主要小部件具有特定的大小
- 如何在sfml中调整窗口大小
- 为什么我不能得到放大和缩小的效果,但必须先调整窗口大小
- 调整窗口大小会导致右边框附近出现涂抹
- ncurses:wgetch在移动/调整窗口大小后无法正确读取
- Qt调整窗口大小以适应滚动区域问题中的纵横比