How do I change color of pixels when using glDrawPixels, my pixels are always red

1.6k Views Asked by At

I have a function that draws pixels 1 by 1 on a window, but what I want to know is how to get the pixels to be drawn in a different color other than red. Thanks in advance. I've tried some stuff like glSetColor, glColor3f, etc. Just to try and get the pixels to display in different colors but nothing seemed to work so far.

#include <GL/glut.h>
#include <iostream>

using namespace std;

float *PixelBuffer;
void setPixel(int, int);

void display();

int size = 400 * 400 * 3;

int main(int argc, char *argv[])
{

    PixelBuffer = new float[400 * 400 * 3];

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

    glutInitWindowSize(400, 400);

    glutInitWindowPosition(100, 100);
    glColor3f(0, 1.0, 0);

    int firstWindow = glutCreateWindow("First Color");



    glClearColor(0, 0, 0, 0); //clears the buffer of OpenGL

  for(int i = 0; i < 20; i++)
  {
    setPixel(i, 10);
  }



    glutDisplayFunc(display);

    glutMainLoop();


    return 0;
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();

    glDrawPixels(400, 400, GL_RGB, GL_FLOAT, PixelBuffer);
    glFlush();
}

void setPixel(int x, int y)
{
  int pixelLocation;
  int width = 400;
  pixLocation = (y * width * 3) + (x * 3);
  PixelBuffer[pixelLocation] = 1;
};
1

There are 1 best solutions below

1
On BEST ANSWER

You specify GL_RGB as format when calling glDrawPixels.

Then you calculate the correct position of the pixel in your buffer on the line:

pixLocation = (y * width * 3) + (x * 3);

But then you only set the Red pixel intensity value on the next line. You can access the other color values in your buffer like this:

PixelBuffer[pixelLocation + 0] = 1; // Red pixel intensity
PixelBuffer[pixelLocation + 1] = 1; // Green pixel intensity
PixelBuffer[pixelLocation + 2] = 1; // Blue pixel intensity