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

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

#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();
}

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值