OpenGL 中一致的手绘线

Consistent Freehand line in OpenGL

我知道如何在opengl中徒手绘制,但我希望鼠标移动速度过快时不要出现空隙。这是我的:

void myMovedMouse(int mouseX, int mouseY)
{
    int x = mouseX;
    int y = IMAGE_Y - mouseY - 1;
    //int brushSize = 20;
    //glRecti(x, y, x + brushSize, y + brushSize);
    drawDot(x, y);
    glFlush();
}

//in main
glutDisplayFunc(myDisplay);
glutMotionFunc(myMovedMouse);

我也试过用GL_LINE_LOOP,当然不行。

将上次更新后的鼠标位置保存在全局变量中。然后使用线路连接到您的新位置。像这样:

int lastMouseX, lastMouseY;

void myMovedMouse(int mouseX, int mouseY)
{
    int x = mouseX;
    int y = IMAGE_Y - mouseY - 1;

    glBegin(GL_LINES);
    glVertex2i(lastMouseX, lastMouseY);
    glVertex2i(x, y);
    glEnd();
    glFlush();

    lastMouseX = x;
    lastMouseY = y;
}

如果您使用鼠标按钮进行绘图,则仅在按下按钮时更新您的最后位置。当再次按下按钮时,还将最后一个位置初始化为鼠标位置。需要初始化,因此您的第一个笔划不会从原点 (0,0) 开始,并且后续笔划不会连接到之前的笔划。

将鼠标位置附加到 std::vector 并使用 GL_LINE_STRIP:

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

std::vector< int > points;
void mouse( int button, int state, int x, int y )
{
    if( state == GLUT_DOWN )
        points.clear();
    points.push_back( x );
    points.push_back( y );
    glutPostRedisplay();
}

void motion( int x, int y )
{
    points.push_back( x );
    points.push_back( y );
    glutPostRedisplay();
}

void display()
{
    glClearColor( 0, 0, 0, 1 );
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    double w = glutGet( GLUT_WINDOW_WIDTH );
    double h = glutGet( GLUT_WINDOW_HEIGHT );
    glOrtho( 0, w, h, 0, -1, 1 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glBegin( GL_LINE_STRIP );
    glColor3ub( 255, 0, 0 );
    for( size_t i = 0; i < points.size(); i += 2 )
    {
        glVertex2i( points[i+0], points[i+1] );
    }
    glEnd();

    glutSwapBuffers();
}

int main( int argc, char** argv )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
    glutCreateWindow( "GLUT" );
    glutMouseFunc( mouse );
    glutMotionFunc( motion );
    glutDisplayFunc( display );
    glutMainLoop();
    return 0;
}