OpenGL从1.0开始--OpenGL显示表(上)

来源:互联网 发布:js random 1 100 编辑:程序博客网 时间:2024/05/16 13:07

这一篇开始,我们给大家带来一点真正的挑战。
让我们来头脑风暴下如何实现窗口重定形函数,使六边形中心位置不受窗口尺寸变化的影响。

#include <Gl/glut.h>#include <math.h>#include <stdlib.h>const double TWO_PI = 6.2831853;GLsizei winWidth = 400, winHeight = 400;//初始化窗口大小GLuint regHex;class screenPt//屏幕坐标类,方便存储和调用{private:    GLint x, y;public:    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;    circCtr.setCoords(winWidth / 2, winHeight / 2);//设置圆中心位置    glClearColor(1.0, 1.0, 1.0, 0.0);//显示窗口颜色为白色    regHex = glGenLists(1);//获得显示表未使用的一个标识符。放轻松,后面会详解    glNewList(regHex, GL_COMPILE);//新建显示表    glColor3f(1.0, 0.0, 0.0);//设置六边形的填充色为红色    glBegin(GL_POLYGON);    for (k = 0; k < 6; k++)    {        theta = TWO_PI*k / 6.0;//每次旋转60度        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);    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);    glutInitWindowPosition(100, 100);    glutInitWindowSize(winWidth, winHeight);    glutCreateWindow("An Example OpenGL Program");    init();    glutDisplayFunc(regHexagon);//图元被绘制    glutReshapeFunc(winReshapeFcn);//窗口重定形    glutMainLoop();}

好了,相信大家爬了半天最想看到的就是效果图了
这里写图片描述
改变下窗口大小又会怎样呢?
这里写图片描述
为什么六边形缩小了?个中疑问留待下篇揭晓。

原创粉丝点击