我对使用 GLUT 还很陌生,我一直在尝试编译一个程序(我发现了 here,第一 react ),它使用鼠标通过记录点击的起点和终点来绘制矩形 -和拖动。
作为一个干净的复制/粘贴,它会编译但不会绘制任何东西。它只是显示一个白色屏幕,即使在将背景颜色更改为黑色之后(在 setup() 函数中)也是如此。我已经阅读了多个来源以验证该程序在其绘制和 reshape 函数中没有遗漏任何内容,而且它们都在那里。
我创建一个窗口,将视口(viewport)设置为窗口尺寸,然后使用 gluOrtho2D 函数设置映射(由于窗口和视口(viewport)的尺寸相同,我将映射设置为窗口尺寸)。鼠标回调记录我左键单击的位置,以及我释放左键单击的位置,然后调用 glutPostRedisplay() 函数以使用新坐标重绘窗口。经过一番调试,我发现坐标被适本地记录和保存,并且以像素为单位(x 和 y 是 0 到窗口维度之间的整数),所以我应该能够从一个顶点到另一个顶点绘制一个矩形使用坐标。但是,正如我所说,它只显示一个白屏。
那么,我绘制矩形的方式有问题吗?我是否错误地映射了窗口?我非常迷茫,如有任何反馈,我们将不胜感激。
EDIT2:我将 glutInitDisplayMode 从 GLUT_SINGLE 更改为 GLUT_DOUBLE,这修复了整个非交互式白屏问题。现在它将用鼠标绘制一个带有翻转 y 坐标(我已修复)的矩形,现在效果很好。非常感谢您的建议。
这是我的程序(EDIT1:添加评论):
#include <cstdlib>
#include <GL/glut.h>
using namespace std;
GLsizei width, height;
struct Position
{
Position() : x(0), y(0) {}
float x;
float y;
};
Position start; // Records left-click location
Position finish; // Records left-click release location
void display()
{
glClear(GL_COLOR_BUFFER_BIT); // clear window
glColor3ub(rand()%256, rand()%256, rand()%256); // generates random color
glBegin(GL_QUADS);
glVertex2f(start.x,start.y);
glVertex2f(finish.x,start.y);
glVertex2f(finish.x,finish.y);
glVertex2f(start.x,finish.y);
glEnd();
glutSwapBuffers(); // display newly drawn image in window
}
void reshape( int w, int h )
{
glViewport( 0, 0, (GLsizei)w, (GLsizei)h ); // set to size of window
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, (float)w, 0.0, (float)h );
width = w; // records width globally
height = h; // records height globally
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void mouse(int button, int state, int x, int y)
{
switch(button)
{
case GLUT_LEFT_BUTTON:
if(state==GLUT_DOWN)
{
start.x = x; //x1
start.y = y; //y1
}
if(state==GLUT_UP)
{
finish.x = x; //x2
finish.y = y; //y2
}
break;
glutPostRedisplay();
}
}
void motion( int x, int y )
{
finish.x = x;
finish.y = y;
glutPostRedisplay();
}
void setup()
{
glClearColor(0.0, 0.0, 0.0, 1.0); // *should* display black background
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,100);
glutCreateWindow("");
setup();
// initializing callbacks
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutMainLoop();
return 0;
}
最佳答案
正如我的评论所建议的那样:
改变:
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
到:
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
关于c++ - 在 GLUT 中用鼠标画一个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18973214/