gpt4 book ai didi

c++ - 从菜单中选择时如何只绘制矩形?

转载 作者:行者123 更新时间:2023-12-04 07:43:40 25 4
gpt4 key购买 nike

我正在编写一个程序,当且仅当用户在菜单中选择它时用鼠标绘制一个矩形,如果用户不选择它就不会绘制。到目前为止,我已经成功地用鼠标绘制了矩形,现在如何创建一个菜单,以便用户可以选择绘制矩形?这是我的程序:

struct Position
{
Position() : x(0), y(0) {}
float x, y;
};
Position start, finish;

void mouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
start.x = finish.x = x;
start.y = finish.y = y;
}
if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
{
finish.x = x;
finish.y = y;
}
glutPostRedisplay();
}

void motion(int x, int y)
{
finish.x = x;
finish.y = y;
glutPostRedisplay();
}

void display()
{
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();

glPushMatrix();
glBegin(GL_LINE_LOOP);
glVertex2f(start.x, start.y);
glVertex2f(finish.x, start.y);
glVertex2f(finish.x, finish.y);
glVertex2f(start.x, finish.y);
glEnd();
glPopMatrix();

glutSwapBuffers();
}

void menu(int choice)
{
switch (choice)
{
case 1:
// What to write in here?
break;
}
glutPostRedisplay();
}

int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640, 480);
glutInitWindowPosition(100, 100);
glutCreateWindow("");

glutCreateMenu(menu);
glutAddMenuEntry("Rectangle", 1);
glutAttachMenu(GLUT_RIGHT_BUTTON);

glutMouseFunc(mouse);
glutMotionFunc(motion);
glutDisplayFunc(display);

glutMainLoop();
}

最佳答案

添加一个变量,指示必须绘制哪个形状:

int shape = 0;
menu 中设置变量:
void menu(int choice)
{
switch (choice)
{
case 1:
shape = 1
break;
}
glutPostRedisplay();
}
绘制场景依赖 shape :
void display()
{
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();

if (shape == 1)
{
glPushMatrix();
glBegin(GL_LINE_LOOP);
glVertex2f(start.x, start.y);
glVertex2f(finish.x, start.y);
glVertex2f(finish.x, finish.y);
glVertex2f(start.x, finish.y);
glEnd();
glPopMatrix();
}

glutSwapBuffers();
}

关于c++ - 从菜单中选择时如何只绘制矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67311180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com