图2.41
#include<windows.h>
#include<gl/glut.h>
struct GLintPoint
{
GLint x,y;
};
//全局变量
GLintPoint corner[2];
bool selected=false;
int screenWidth=640,screenHeight=480;
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glColor3f(1.0f,1.0f,1.0f);
if(selected)
{
glBegin(GL_QUADS);
glVertex2i(corner[0].x,corner[0].y);
glVertex2i(corner[0].x,corner[1].y);
glVertex2i(corner[1].x,corner[1].y);
glVertex2i(corner[1].x,corner[0].x);
glEnd();
}
glutSwapBuffers(); //实现双缓冲
}
void myMouse(int button,int state,int x,int y)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
{
corner[0].x=x;
corner[0].y=screenHeight-y;
selected=true;
}
glutPostRedisplay(); //标记当前窗口需要重新绘制,通过glutMainLoop下一次
//循环时,窗口显示将被回调以重新显示窗口的正常面板
}
void myPassiveMotion(int x,int y)
{
corner[1].x=x;
corner[1].y=screenHeight-y;
glutPostRedisplay();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
//初始化窗口
glutInitWindowSize(screenWidth,screenHeight);
glutInitWindowPosition(0,0);
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE); //设置初始显示模式
glutCreateWindow("Rubber Rect Demo"); //创建窗口
//设置投影矩阵
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,screenWidth,0,screenHeight);
glMatrixMode(GL_MODELVIEW);
//清渲染面
glClearColor(0.0f,0.0f,0.0f,0.0f); //背景为黑色
glViewport(0,0,screenWidth,screenHeight);
glutMouseFunc(myMouse);
glutDisplayFunc(myDisplay);
glutPassiveMotionFunc(myPassiveMotion);
glutMainLoop();
return(0);
}