打开GL颜色选择器不着色对象

时间:2012-10-27 06:06:34

标签: c++ opengl colors draw picker

我用C ++编写了一个使用OpenGL的颜色选择器,但我无法弄清楚如何使用我存储的颜色为多边形(或其他任何事情)着色。我是否需要将绘制函数放在某种循环中,或者有更好的方法吗?

#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 个答案:

答案 0 :(得分:1)

您只需添加以下行:

glutPostRedisplay();

在鼠标回调函数结束时。

这是因为你总是必须明确地告诉过时何时刷新窗口。