2012-10-27 37 views
1

我已经使用OpenGL在C++中编写了一个颜色选择器,但我无法弄清楚如何用我存储的颜色为多边形着色(或其他任何事情)。我是否需要将绘图函数放在某种循环中,还是有更好的方法来做到这一点?Open GL颜色选取器没有着色对象

#ifdef __APPLE__ 
# include <OpenGL/gl.h> 
# include <OpenGL/glu.h> 
# include <GLUT/glut.h> 
#else 
# include <GL/gl.h> 
# include <GL/glu.h> 
# include <GL/glut.h> 
#endif 

#include <iostream> 
#include <cmath> 
using namespace std; 

#define WIDTH 750 
#define HEIGHT 750 

int i=0,mousex, mousey; 

float pick[3]; 

bool mouseleftdown = false; 



void hex(void){ 
glBegin(GL_POLYGON); 
    glColor3f(1,0,0);   //red 
    glVertex2f(0, 2);   //top 
    glColor3f(1,.38,.01);  //orange 
    glVertex2f(2, 1);   //top right 
    glColor3f(1,1,0);   //yellow 
    glVertex2f(2, -1);   //bottom right 
    glColor3f(0,1,0);   //green 
    glVertex2f(0, -2);   //bottom 
    glColor3f(0,0,1);   //blue 
    glVertex2f(-2, -1);   //bottom left 
    glColor3f(.8,0,.8);   //purple 
    glVertex2f(-2, 1);   //top left 
glEnd(); 

glEnd(); 
} 

void square(void){ 
glBegin(GL_POLYGON); 
glVertex2i(1, -1); 
glVertex2i(1, 1); 
glVertex2i(-1, 1); 
glVertex2i(-1, -1); 
glEnd(); 
} 

void mouse(int button, int state, int x, int y){ 
// Save the left button state 
/*if (button == GLUT_LEFT_BUTTON) 
{ 
    if (state == GLUT_DOWN) 
    glutPostRedisplay(); // Left button has changed; redisplay! 
}*/ 


// Save the mouse position 
mousex = x; 
mousey = y; 

glReadPixels(mousex , mousey , 1 , 1 , GL_RGB , GL_FLOAT , &pick); 
cout << pick[0] <<"pick"; 
cout << " mouse x " << mousex << "\n"; 
cout << " mouse y " << mousey << "\n"; 
fflush(stdout); 

cout << "pick R: " << pick[1] << "\n"; 
cout << "pick G: " << pick[0] << "\n"; 
cout << "pick B: " << pick[2] << "\n"; 
} 



void draw(void){ 
glClear(GL_COLOR_BUFFER_BIT); 

glPushMatrix(); 
glScalef(20,20,1); 
    hex(); 
glPopMatrix(); 

glPushMatrix(); 
glTranslatef(100,100,0); 
glColor3f(pick[1],pick[0],pick[2]); 
glScalef(20,20,1); 
square(); 
glPopMatrix(); 

glFlush(); 

} 

void my_init(void){ 
//glClearColor(0, 0, 0, 1);    //sets clear color 
glLineWidth(4); 
gluOrtho2D(-100, 100, -100, 100);  //sets origin 
} 

int main(int argc, char* argv[ ]){ 
glutInit(&argc, argv); 
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); 
glutInitWindowSize(WIDTH, HEIGHT); 
glutCreateWindow("Color Picker"); 
glutDisplayFunc(draw); 
glutMouseFunc(mouse); 

my_init(); 

glClearColor(1, 1, 1, 0); 

glutMainLoop();       //listens for events 

return 0; 
} 

回答

1

你要简单地添加一行:

glutPostRedisplay(); 

在你的鼠标回调函数结束。

这是因为您总是必须在刷新窗口时明确告诉过量。

+0

非常感谢!那就是诀窍! –