glViewport是OpenGL中的一個函數。計算機圖形學中,在屏幕上打開窗口的任務是由窗口系統,而不是OpenGL負責的。glViewport在默認情況下,視口被設置為占據打開窗口的整個像素矩形,窗口大小和設置視口大小相同,所以為了選擇一個更小的繪圖區域,就可以用glViewport函數來實現這一變換,在窗口中定義一個像素矩形,最終將圖像映射到這個矩形中。例如可以對窗口區域進行划分,在同一個窗口中顯示分割屏幕的效果,以顯示多個視圖/
glViewport(GLint x,GLint y,GLsizei width,GLsizei height)為其函數原型。
X,Y————以像素為單位,指定了
視口的左下角(在第一象限內,以(0,0)為原點的)位置。
width,height————表示這個視口矩形的寬度和高度,根據窗口的實時變化重繪窗口。
// OpenGL_03.cpp : 定義控制台應用程序的入口點。
//
#include "stdafx.h"
#include<gl/glut.h>
void display()
{
//畫分割線 ,分成四個視圖區域
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
glViewport(0, 0, 400, 400);
glBegin(GL_LINES);
glVertex2f(-1.0, 0);
glVertex2f(1.0, 0);
glVertex2f(0, -1.0);
glVertex2f(0, 1.0);
glEnd();
//定義左下角區域
glColor3f(0.0, 1.0, 0.0);
glViewport(0, 0, 200, 200);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
//定義右上角區域
glColor3f(0.0, 0.0, 1.0);
glViewport(200, 200,200, 200);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
//定義在左上角的區域
glColor3f(1.0, 0.0, 0.0);
glViewport(0, 200, 200, 200);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
//定義在右下角的區域
glColor3f(1.0, 1.0, 1.0);
glViewport(200, 0, 200, 200);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
glFlush();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(100, 100);
glutInitWindowSize(400, 400);
glutCreateWindow("glViewport");
glutDisplayFunc(display);
//0100;
glutMainLoop();
return 0;
}

