GLUT Tutorials X: Repaint and Picking Rectangle
博客转自:https://www.cnblogs.com/yangxi/archive/2012/02/21/2361801.html
OpenGL小程序,实现了点击屏幕中矩形拖动的功能。
#include <windows.h> #include <GL/glut.h> static GLint point[2] = { 400, 300 }; // 矩形中心位置点坐标 static bool changeState = FALSE; // 点击时鼠标位置是否在矩形中 // 绘制函数 void display() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 0.0, 1.0); glBegin(GL_POLYGON); glVertex2i(point[0] - 25, point[1] - 25); glVertex2i(point[0] + 25, point[1] - 25); glVertex2i(point[0] + 25, point[1] + 25); glVertex2i(point[0] - 25, point[1] + 25); glEnd(); glFlush(); } // 初始化函数 void init() { glClearColor(0.0, 0.0, 0.0, 0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 800, 600, 0, -1.0, 1.0); } // 键盘响应函数 void keyboard(unsigned char key, int x, int y) { switch (key) { case 27: exit(0); break; default: break; } } // 鼠标点击响应函数 void mouse(int button, int state, int x, int y) { if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN)) { // 判断鼠标位置是否在矩形中 if (abs(x - point[0]) < 25 && abs(y - point[1])<25) { changeState = TRUE; } } else if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_UP)) { changeState = FALSE; } } // 鼠标移动响应函数 void mouseMove(int x, int y) { glClear(GL_COLOR_BUFFER_BIT); if (changeState == TRUE) { point[0] = x; point[1] = y; glutPostRedisplay(); // 重绘函数 } } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(800, 600); glutInitWindowPosition(100, 100); glutCreateWindow("Redisplay"); init(); glutDisplayFunc(display); glutMouseFunc(mouse); glutMotionFunc(mouseMove); glutKeyboardFunc(keyboard); glutMainLoop(); return 0; }
显示效果