使用glDrawPixels()在OpenGL上绘制像素

时间:2018-10-08 00:16:07

标签: c++ opengl glut

我想在C ++中制作makePixel(...)函数,该函数可以将像素放置在指定的x和y中。但是我不知道为什么我的方法行不通。

#include "glut.h"

int WIDTH, HEIGHT = 400;
GLubyte* PixelBuffer = new GLubyte[WIDTH * HEIGHT * 3];

void display();


int main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);

    glutInitWindowSize(WIDTH, HEIGHT); 
    glutInitWindowPosition(100, 100); 

    int MainWindow = glutCreateWindow("Hello Graphics!!"); 
    glClearColor(0.5, 0.5, 0.5, 0);

    makePixel(200,200,0,0,0,PixelBuffer);

    glutDisplayFunc(display); 
    glutMainLoop();
    return 0;
}



void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glDrawPixels(WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, PixelBuffer);
    glFlush(); 
}

在“ glut.h”中

void makePixel(int x, int y, int r, int g, int b, GLubyte* pixels)
{
    if (0 <= x && x < window.width && 0 <= y && y < window.height) {
        int position = (x + y * window.width) * 3;
        pixels[position] = r;
        pixels[position + 1] = g;
        pixels[position + 2] = b;
    }
}

1 个答案:

答案 0 :(得分:1)

int WIDTH, HEIGHT = 400;仅将400分配给HEIGHT,而不分配HEIGHTWIDTH,就像您的代码所假定的那样。 WIDTH尚未初始化(或者可能是默认构造的,我不确定C ++规范在这种情况下的要求是什么;我在运行时在系统上看到0时间)。

一起:

screenshot of white pixel

#include <GL/glut.h>

int WIDTH = 400;
int HEIGHT = 400;
GLubyte* PixelBuffer = new GLubyte[WIDTH * HEIGHT * 3];

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glDrawPixels(WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, PixelBuffer);
    glutSwapBuffers(); 
}

void makePixel(int x, int y, int r, int g, int b, GLubyte* pixels, int width, int height)
{
    if (0 <= x && x < width && 0 <= y && y < height) {
        int position = (x + y * width) * 3;
        pixels[position] = r;
        pixels[position + 1] = g;
        pixels[position + 2] = b;
    }
}

int main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);

    glutInitWindowSize(WIDTH, HEIGHT); 
    glutInitWindowPosition(100, 100); 

    int MainWindow = glutCreateWindow("Hello Graphics!!"); 
    glClearColor(0.0, 0.0, 0.0, 0);

    makePixel(200,200,255,255,255,PixelBuffer, WIDTH, HEIGHT);
    glutDisplayFunc(display); 
    glutMainLoop();
    return 0;