我想在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;
}
}
答案 0 :(得分:1)
int WIDTH, HEIGHT = 400;
仅将400
分配给HEIGHT
,而不分配HEIGHT
和WIDTH
,就像您的代码所假定的那样。 WIDTH
尚未初始化(或者可能是默认构造的,我不确定C ++规范在这种情况下的要求是什么;我在运行时在系统上看到0
时间)。
一起:
#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;