一致的手绘线在OpenGL

Consistent Freehand line in OpenGL

本文关键字:OpenGL 手绘      更新时间:2023-10-16

我知道如何在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,但当然没有工作。

将鼠标位置附加到std::vector &use 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;
}

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

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)开始,并且以后的笔画不会连接到前面的笔画。