通过一天的学习,将书中的代码敲打下来,有些事情,你不做的话永远感觉难,继续坚持下去,目前,图形学的编程还没有给我带来激情,学起来很吃力.
经过前面的学习,我们先来看一看最简单的例子:点
#include
#include
void display()
{
glClear(GL_COLOR_BUFFER_BIT);//没有这一句,则背景使用的是当前的屏幕背景
glPointSize(2.0);//定义点的大小
glBegin(GL_POINTS);
glColor3f(1.0,1.0,1.0);//定义点的颜色
glVertex2f(-0.5,-0.5);
glColor3f(1.0,0.0,0.0);
glVertex2f(-0.5,0.5);
glColor3f(0.0,1.0,0.0);
glVertex2f(0.5,-0.5);
glColor3f(0.0,0.0,1.0);
glVertex2f(0.5,0.5);
glEnd();
glFlush();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutCreateWindow("POINTS!");
glutDisplayFunc(display);
glutMainLoop();
}
效果图如下:
再来看第二个例子:线,这个图元分为三部分
GL_LINES:
#include//本种用法每一对顶点画一条线段
#include
void display()
{
float i;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);//设置颜色
glBegin(GL_LINES);
glVertex2f(-0.5,0.5);
glVertex2f(10,8);
glVertex2f(10,8);
glVertex2f(5,6);//不知为什么无法画多条直线
glEnd();
glFlush();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutCreateWindow("LiNES!");
glutDisplayFunc(display);
glutMainLoop();
}
效果图如下:
2.GL_LINES_STRIP:每条线段的终点都是下条线段的起点
#include
#include
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINE_STRIP);
glColor3f(1.0,0.0,0.0);
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);
glutCreateWindow("LINES_STRIP");
glutDisplayFunc(display);
glutMainLoop();
}
效果图如下:
3.GL_LINE_LOOP:和GL_LINE_STRIP一样,只不过最后一个顶点自动连接第一个顶点
#include
#include
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINE_LOOP);
glColor3f(1.0,0.0,0.0);
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);
glutCreateWindow("LOOP!");
glutDisplayFunc(display);
glutMainLoop();
}
线段的属性包括颜色线段粗细以及一个条纹图案后者允许我们创建虚线
下图效果与上图一样,只不过定义的线段宽度为4.0;
#include
#include
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
/*与前一个的不同之处
*/
glBegin(GL_LINE_LOOP);
glColor3f(1.0,0.0,0.0);
glLineWidth(4.0);//线宽
glLineStipple(3,0xcccc);//位模式`
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);
glutCreateWindow("LOOP!");
glutDisplayFunc(display);
glutMainLoop();
}
效果图如下:
二 下面的代码:加入了键盘事件,也就是使应用程序能够接受程序员的指令,
我们将一个打开的窗口通过自定义键盘'q'或者'Q'键关闭窗口
#include
#include
#include
#include
using namespace std;
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
// glClearColor//清除颜色
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();
}
void mykey(unsigned char key,int x,int y)//使用键盘处理交互信息
{
if(key=='q' || key=='Q' || key=='\27')
exit(0);
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutCreateWindow("Hello,world!");
glutDisplayFunc(display);//glutDisplayFunc(void (*func)(void))
glutKeyboardFunc(mykey);//使用键盘
// glutMouseFunc(mymouse);
glutMainLoop();//导致程序进入一个事件
}