因此,我正在使用C++編寫一個使用openGl的程序,我想加載一個圖像然後以NxN網格形式顯示它。 予加載的圖像和存儲在數組中它的數據,然後進行到用下面的方法來實現我的目標:使用openGl顯示pgm圖像
void fillGrid(){
ifstream myfile("paper.pgm");
ofstream otherfile;
otherfile.open("test.txt");
string line;
string buffer;
fstream afile;
if (myfile.is_open())
{
int counter=0;
while (getline(myfile, line))
{
if(counter>2){
buffer=buffer+line;
}
counter++;
}
pixels=new float[1600];
int i=0;
string delimiters = " ,";
size_t current;
size_t next = -1;
do
{
current = next + 1;
next = buffer.find_first_of(delimiters, current);
if(i<=1600){
pixels[i]=myAtof (buffer.substr(current));
paper[i]=pixels[i];
}
i++;
}
while (next != string::npos);
for(int j=0;j<=1600;j++){
otherfile<<paper[j]<<" "<< j<<endl;
}
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glBindTexture(GL_TEXTURE_2D, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 140, 140, 0, GL_RGB, GL_FLOAT, paper);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_REPEAT);
}
}
該功能打開包含圖像數據的文件,裝載在像素圖像數組,然後在紙數組,我用glTexImage2D。 MyAtof()是我構建的一個函數,用於將字符串轉換爲浮點數。數據正確地從文件傳遞到數組,我已經測試過了。 後療法fillGrid函數以下函數被調用做T重繪:
void drawGrid2(void)
{
for(int i=-240;i<240;i+=40){
for(int j=-300;j<=300;j+=40){
drawSquare2(i,j);
}
}
}
而且也:
void drawSquare2(int x,int y)
{
glBindTexture(GL_TEXTURE_2D, 1);
glBegin(GL_QUADS); //Start drawing quad
glVertex2f(x,y); //first coordinate x y
glVertex2f(x+40,y); //second coordinate
glVertex2f(x+40,y+40); //third coordinate
glVertex2f(x,y+40); //last coordinate
glEnd(); //Stop drawing quads
glFlush();
}
主營:
int main (int argc, char** argv)
{
glutInit (&argc, argv); // Initialize GLUT.
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // Set display mode.
glutInitWindowPosition (0, 0); // Set top-left display-window position.
glutInitWindowSize (600, 500); // Set display-window width and height.
glutCreateWindow ("Main"); // Create display window.
init(); // Execute initialization procedure.
glutDisplayFunc (display); // Send graphics to display window.
glutKeyboardFunc(processEscKey);
glutMainLoop(); // Display everything and wait.
return 0;
}
其它功能:
void init (void)
{
// glClearColor (1.0, 1.0, 1.0, 0.0); // Set display-window color to white.
glClearColor (0.0, 0.0, 0.0, 1.0);//black
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glMatrixMode (GL_PROJECTION); // Set projection parameters.
gluOrtho2D(-300,300,-300,300);//0,width,0,height
}
void processEscKey(unsigned char key, int x, int y)
{
if(key==27){
exit(0);
}
else if(key==98){
fillGrid();
drawGrid2();
}
}
這是使用openGl創建紋理並顯示圖像的正確方法嗎?
該文件編譯但結果不是我想要的。 我想要一個15x15的正方形網格,每個正方形都包含圖像。 重繪前的結果是this。
重繪後的結果是this。
我對第一個repaint和第二個使用了不同的函數。 由於第一個工作,我沒有發佈。
有可能我在發送到glTexImage2d的數據中使用了錯誤的格式? –