OpenGL多视口变换函数:glViewport使用
glViewport是OpenGL中的一个函数。计算机图形学中,在屏幕上打开窗口的任务是由窗口系统,而不是OpenGL负责的
1.功能glViewport在默认情况下,视口被设置为占据打开窗口的整个像素矩形,如图1,窗口大小和设置视口大小相同,所以为了选择一个更小的绘图区域,就可以用glViewport函数来实现这一变换,在窗口中定义一个像素矩形,最终将图像映射到这个矩形中。例如可以对窗口区域进行划分,在同一个窗口中显示分割屏幕的效果,以显示多个视图。
2.参数
glViewport(GLint x,GLint y,GLsizei width,GLsizei height)为其函数原型。
//计算gluLookAt矩阵 #pragma once #include <windows.h> #define GLUT_DISABLE_ATEXIT_HACK #include <gl/glut.h> #include <atlimage.h> #include <math.h> //不显示控制台窗口 //#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"") float g_RotAngle = 0.5; void TimerFunction(int value) { g_RotAngle += 1.0; if (g_RotAngle>=360) { g_RotAngle = 0; } glutPostRedisplay(); glutTimerFunc(10, TimerFunction, 1); } void display() { //glMatrixMode( GL_MODELVIEW ); //glLoadIdentity(); glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 0.0, 0.0); //画分割线,分成四个视见区 glViewport(0, 0, 800, 600); glBegin(GL_LINES); glVertex2f(-1.0, 0); glVertex2f(1.0, 0); glVertex2f(0.0, -1.0); glVertex2f(0.0, 1.0); glEnd(); //定义在左下角的区域 glColor3f(0.0, 1.0, 0.0); glViewport(0, 0, 400, 300); glPushMatrix(); glRotatef(g_RotAngle, 0.0, 1.0, 0.0); glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glPopMatrix(); //定义在右上角的区域 glColor3f(0.0, 0.0, 1.0); glViewport(400, 300, 400, 300);//一定要注意,后面这两个参数是高度和宽度,而不是坐标 glPushMatrix(); glRotatef(-g_RotAngle, 0.0, 1.0, 0.0); glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glPopMatrix(); //定义在左上角的区域 glColor3f(1.0, 0.0, 1.0); glViewport(0, 300, 400, 300);//一定要注意,后面这两个参数是高度和宽度,而不是坐标 glPushMatrix(); glRotatef(-2*g_RotAngle, 0.0, 1.0, 0.0); glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glPopMatrix(); //定义在右下角 glColor3f(1.0, 1.0, 0.0); glViewport(400, 0, 400,300);//一定要注意,后面这两个参数是高度和宽度,而不是坐标 glPushMatrix(); glRotatef(-3*g_RotAngle, 0.0, 1.0, 0.0); glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glPopMatrix(); glFlush(); } void init() { glClearColor(0.0, 0.0, 0.0, 0.0); glColor3f(1.0, 1.0, 1.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //定义剪裁面 gluOrtho2D(-1.0, 1.0, -1.0, 1.0); //glViewport( 0, 0, 200, 200 ); //放在这里不好使 } int main(int argc, char ** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition(100, 100); glutInitWindowSize(800, 600); glutCreateWindow("OpenGL多视口编程"); glutDisplayFunc(display); init(); glutTimerFunc(1, TimerFunction, 1); glutMainLoop(); }4.截图效果: