OpenGL显示窗口重定形函数
在介绍性的OpenGL程序中,我们讨论了建立初始显示窗口的函数。但是在生成图形后,常需要用鼠标将显示窗口拖到屏幕的另一位置或改变其形状。改变显示窗口的尺寸可能改变其纵横比并引起对象形状的改变。
为了允许对显示窗口尺寸的改变做出反应,GLUT库提供下面的函数:
在介绍性的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 ();
}