標籤:
OpenGL顯示視窗重定形函數
在介紹性的OpenGL程式中,我們討論了建立初始顯示視窗的函數。但是在產生圖形後,常需要用滑鼠將顯示視窗拖到螢幕的另一位置或改變其形狀。改變顯示視窗的尺寸可能改變其縱橫比並引起對象形狀的改變。
為了允許對顯示視窗尺寸的改變做出反應,GLUT庫提供下面的函數:
glutReshapeFunc(winReshapeFcn);
該函數可和其他GLUT函數一起放在程式的主過程中,它在顯示視窗尺寸輸入後立即啟用。該GLUT函數的變數是接受新視窗寬度和高度的過程名。我們可以接著使用新尺寸去重新設定投影參數並完成任何其他動作,包括改變顯示視窗顏色。另外,我們可以儲存寬度和高度給程式中的其他過程使用。
作為一個例子,下列程式展示了怎樣構造winReshapeFcn過程。命令glLoadIdentity包含在重定形函數中,從而使前面任意的投影參數值對新的投影設定不起作用。該程式顯示了討論的規則六邊形。儘管本例中的六邊形中心(在圓的中心位置)用顯示視窗參數的概念描述,但是該六邊形的位置不受顯示視窗尺寸的任何改變的影響。這是因為六邊形在顯示表中定義,並且僅僅是最初的中心座標儲存在表中。如果希望在改變顯示視窗尺寸時改變六邊形的位置,則需要使用另一種方法來定義六邊形或改變顯示視窗的座標參考。圖3.64給出了該程式的輸出。
#include <GL/glut.h>#include <math.h>#include <stdlib.h>const double TWO_PI = 6.2831853;/* Intial display-window size.*/GLsizei winWidth = 400, winHeight = 400;GLuint regHex;class screenPt{ private: GLint x,y;public:/* Default Constructor: initializes coordinate position to (0, 0).*/screenPt ( ) { x = y = 0;}void setCoords (GLint xCoord, GLint yCoord) { x = xCoord; y = yCoord;}GLint getx () const { return x;}GLint gety () const { return y;}};static void init (void){ screenPt hexVertex, circCtr;GLdouble theta;GLint k;/* Set circle center coordinates.*/circCtr.setCoords (winWidth / 2, winHeight/2);glClearColor (1.0, 1.0, 1.0, 0.0);//Display-window color = white./* Set up a display list for a red regular hexagon. * Vertices for the hexagon are Six equally spaced * points around the circumference of a circle. */ regHex = glGenLists (1); // Get an identifier for the display list. glNewList (regHex, GL_COMPILE); glColor3f (1.0, 0.0, 0.0); // Set fill color for hexagon to red.glBegin (GL_POLYGON); for (k = 0; k < 6; k++){ theta = TWO_PI * k / 6.0; hexVertex.setCoords (circCtr.getx () + 150 * cos (theta), circCtr.gety () + 150 * sin (theta)); glVertex2i (hexVertex.getx (), hexVertex.gety ()); } glEnd ();glEndList ();}void regHexagon (void){ glClear (GL_COLOR_BUFFER_BIT);glCallList (regHex);glFlush();}void winReshapeFcn (int newWidth, int newHeight){ glMatrixMode (GL_PROJECTION);glLoadIdentity ( );gluOrtho2D (0.0, (GLdouble) newWidth, 0.0, (GLdouble) newHeight);glClear (GL_COLOR_BUFFER_BIT);}void main (int argc, char** argv){ glutInit (&argc, argv);glutInitDispayMode (GLUT_SINGLE | GLUT_RGB);glutInitWindowPosition (100, 100);glutInitWindowSize (winWidth, winHeight);glutCreateWinow ("Reshape-Function & Display-List Example");init ( );glutDisplayFunc (regHexagon);glutReshapeFunc (winReshapeFcn);glut MainLoop ();}
電腦圖形學(二)輸出圖元_19_顯示視窗重定形函數