SWUST 计算机图形学 实验一 绘制任意斜率直线

发布于 2021-07-03  122 次阅读


一、鼠标处理函数

void MouseClick(int button, int state, int x, int y)
{
    //左键按下为起点,左键抬起为终点
    if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON)
    {
        y = HEIGHT - y;
        FirstPoint.x = x;
        FirstPoint.y = y;
    }
    else if(state == GLUT_UP && button == GLUT_LEFT_BUTTON)
    {
        y = HEIGHT - y;
        SecondPoint.x = x;
        SecondPoint.y = y;
        DrawLine();
    }
}

  这里要求左键按下去到抬起来之间画一条直线。这里再配合glutMouseFunc(MouseClick)使用即可。

二、获取鼠标的屏幕坐标

void MouseMove(int x, int y)
{
    std::cout << "(" << x << ", " << y << ")" << std::endl;
}

  这里搭配glutMotionFunc(MouseMove)使用,不过只读取鼠标按键按下后的坐标。

三、完整代码

#include <GL/glut.h>
#include <iostream>
#include <glm/glm.hpp>

/*---常量---*/
const int HEIGHT(400);
const int WIDTH(400);

/*---变量---*/
glm::vec2 FirstPoint{ 0, 0 };
glm::vec2 SecondPoint{ 0, 0 };
//画线记录两点

/*---函数---*/
void Display();
//显示函数
void Reshape(int, int);
//投影变换函数
void DrawLine();
//画线函数
void MouseClick(int, int, int, int);
//鼠标点击函数
void MouseMove(int, int);
//鼠标坐标函数

/*---主函数---*/
int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    //对GLUT进行初始化

    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    //设置显示窗口缓存和色彩模型
    //这里使用单缓存和RGB颜色模组

    glutInitWindowSize(WIDTH, HEIGHT);
    glutInitWindowPosition(50, 100);
    //窗口大小和位置初始化

    glClearColor(0, 0, 0, 1);
    //窗口颜色

    glutCreateWindow("Draw a line");
    //窗口名

    glutDisplayFunc(Display);
    glutMotionFunc(MouseMove);
    glutMouseFunc(MouseClick);
    glutReshapeFunc(Reshape);

    glutMainLoop();
}

void Display()
{
    glClear(GL_COLOR_BUFFER_BIT);
}

/*--投影函数---*/
void Reshape(int w, int h)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, WIDTH, 0, HEIGHT);
}

/*---画线函数---*/
void DrawLine()
{
    glColor3f(0, 1.0, 1.0);
    //颜色选的cyan

    glClear(GL_COLOR_BUFFER_BIT);
    //刷新缓冲区

    glLineWidth(5);
    //线条宽度:5个像素

    glBegin(GL_LINES);
    glVertex2i(FirstPoint.x, FirstPoint.y);
    glVertex2i(SecondPoint.x, SecondPoint.y);
    glEnd();
    //画线

    FirstPoint = glm::vec2{ 0, 0 };
    SecondPoint = glm::vec2{ 0,0 };
    //clear

    glFlush();
    //刷新缓冲区
}

/*--鼠标处理函数--*/
void MouseClick(int button, int state, int x, int y)
{
    //左键按下为起点,左键抬起为终点
    if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON)
    {
        y = HEIGHT - y;
        FirstPoint.x = x;
        FirstPoint.y = y;
    }
    else if(state == GLUT_UP && button == GLUT_LEFT_BUTTON)
    {
        y = HEIGHT - y;
        SecondPoint.x = x;
        SecondPoint.y = y;
        DrawLine();
    }
}

/*---鼠标坐标函数---*/
void MouseMove(int x, int y)
{
    std::cout << "(" << x << ", " << y << ")" << std::endl;
}