获取并设置像素的颜色

get and set color of pixel

本文关键字:颜色 像素 设置 获取      更新时间:2023-10-16

我需要为像素设置颜色。

当我尝试设置某个像素的颜色时(通过单击鼠标左键)。我的鼠标功能。

void mouse(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
    pixel *p = new pixel();
    p->x = x;
    p->y = HEIGHT - y;
    stack.push(p);
    float arr[3];
    readPixel(p->x, p->y, arr);
    std::cout<<"pixel color: ";
    std::cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<std::endl;
    drawPixel(p->x, p->y);
}
}

这里readPixel方法

void readPixel(int x, int y, float (&a)[3]) {
GLubyte arr[3];
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, arr);
a[0] = (float)arr[0] / 255.0f;
a[1] = (float)arr[1] / 255.0f;
a[2] = (float)arr[2] / 255.0f;
};

问题在于设置像素的颜色。我使用字段xy创建结构pixel。当我单击左按钮时,对象pixel被添加到堆栈中。当我尝试为像素设置颜色(绘制它)时 - 像素在方法 drawPixel 中不会改变其颜色

void draw() {
glBegin(GL_POINTS);
if (!stack.empty()) {
    drawPixel(stack.top()->x, stack.top()->y);
    stack.pop();
}
glEnd();
glFlush();
};
void drawPixel(int x, int y) {
glRasterPos2i(x, y); 
glDrawPixels(1, 1, GL_RGB, GL_UNSIGNED_BYTE, &val);
};

&val在哪里float val[3] = { 1.0, 1.0, 0.0 };所以问题是如何为坐标为 x 和 y 的像素设置颜色?

解决方案是将GL_UNSIGNED_BYTE更改为GL_FLOAT,而不是从堆栈中pop项目