GLUT Tutorials X: Repaint and Picking Rectangle

Posted flyinggod

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

 显示效果

技术图片

以上是关于GLUT Tutorials X: Repaint and Picking Rectangle的主要内容,如果未能解决你的问题,请参考以下文章

GLUT Tutorials 10: 修改菜单

GLUT Tutorials 17:子窗口

GLUT Tutorials 8: GLUT菜单

GLUT Tutorials 8: GLUT子菜单

GLUT Tutorials 17:子窗口的reshape

GLUT Tutorials 18:多窗口的rendering