如何使用OpenGL在鼠标拖动上绘制连续点

时间:2015-09-13 04:05:12

标签: opengl

我正在制作一个基本的OpenGL程序,在Windows上喜欢PAINT程序

说明:如果我在窗口屏幕上拖动鼠标,那么在我释放按钮(左)后,会出现一个连续点,显示拖动鼠标的路径。

我的代码只适用于屏幕上的一个点。我想画点线,但我不知道我做了什么。

这是我的代码:

#include <windows.h>
#include <math.h>
#include <gl/glut.h>
#include <gl/gl.h>
void myDisplay(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glFlush();
}
void myMouse(int button, int state, int x, int y)
{
    int yy;
    yy = glutGet(GLUT_WINDOW_HEIGHT);
    y = yy - y; /* In Glut, Y coordinate increases from top to bottom */
    glColor3f(1.0, 0, 0);
    if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
    {
        glBegin(GL_POINTS);
        glVertex2i(x, y);
        glEnd();
    }
    glFlush();
}
void myInit(void)
{
    glClearColor(1.0f, 1.0f, 1.0f, 0.0);
    glColor3f(1.0f, 1.0f, 1.0f);
    glPointSize(5.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
void main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(640, 480);
    glutInitWindowPosition(100, 150);
    glutCreateWindow("Draw Pixel");
    glutDisplayFunc(myDisplay);
    glutMouseFunc(myMouse);
/*glutMotionFunc(myPressedMove);*/
    myInit();
    glutMainLoop();
}

1 个答案:

答案 0 :(得分:1)

将鼠标坐标附加到glutMouseFunc()中的数组,发出glutPostRedisplay(),并在glutDisplayFunc()中绘制数组:

#include <gl/glut.h>
#include <vector>

std::vector< float > points;
void myMouse(int button, int state, int x, int y)
{
    int yy;
    yy = glutGet(GLUT_WINDOW_HEIGHT);
    y = yy - y; /* In Glut, Y coordinate increases from top to bottom */
    if( (button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN) )
    {
        points.push_back(x);
        points.push_back(y);
    }

    glutPostRedisplay();
}

void myDisplay(void)
{
    glClearColor(1.0f, 1.0f, 1.0f, 0.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 640.0, 0.0, 480.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glPointSize(5.0);
    glBegin(GL_POINTS);
    glColor3f(1.0f, 1.0f, 1.0f);
    for (size_t i = 0; i < points.size(); i += 2)
    {
        glVertex2i( points[i], points[i+1] );
    }
    glEnd();

    glFlush();
}

void main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(640, 480);
    glutInitWindowPosition(100, 150);
    glutCreateWindow("Draw Pixel");
    glutDisplayFunc(myDisplay);
    glutMouseFunc(myMouse);
    glutMainLoop();
}