图像无法在正方形上正确映射

时间:2016-11-24 03:43:09

标签: opengl graphics

我附加了我的代码,用于在正方形上映射图像但图像未正确映射Image to be mapped

最终图像正在平铺。

请告诉我如何解决此问题。

GLuint LoadTexture( const char * filename )
{

  GLuint texture;
  int width, height;
  unsigned char * data;
  FILE * file;
  file = fopen( filename, "rb" );
  if ( file == NULL )
    {
      printf("\nThe file is not found"); 
       return 0;
     }
   width = 512;
   height = 512;
   data = (unsigned char *)malloc( width * height * 3 );
   //int size = fseek(file,);
   fread( data, width * height * 3, 1, file );
   fclose( file );
   glGenTextures( 1, &texture );
   glBindTexture( GL_TEXTURE_2D, texture );
   glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_DECAL );
   glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST );
   glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR );
   glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_CLAMP );
   glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_CLAMP );
   gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,GL_RGB, GL_UNSIGNED_BYTE,   data );
free( data );
return texture;
}

/////////////////////////////////////////////// ////////////////////////////////

void display(void)
{

// CLEAR THE WINDOW
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
light();
glPushMatrix();
glLoadIdentity(); 
glTranslatef(0,0,-5);
glViewport(0, 0, window_width, window_height/2);
    glLoadIdentity();
    gluLookAt(0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
drawObject();
glFlush();
glutSwapBuffers();

}

/////////////////////////////////////////////// //////////////

  void drawSquare()

{
   glBegin(GL_QUADS);              // Each set of 4 vertices form a quad
  //  glColor3f(1.0f, 0.0f, 0.0f); // Red
   glTexCoord2f(0.0f, 1.0f);  
   glVertex2f(-0.2f, 0.2f);
   glTexCoord2f(1.0f, 1.0f);// x, y
   glVertex2f( 0.2f, 0.2f);
   glTexCoord2f(1.0f, 0.0f);
   glVertex2f( 0.2f,  -0.2f);
   glTexCoord2f(0.0f, 0.0f);
   glVertex2f(-0.2f,  -0.2f);
glEnd();



}

/////////////////////////////////////////////// /////////////////////////

    void drawObject(void)

    {   
      // push the current matrix
      glPushMatrix();
      // apply the translation
      glEnable(GL_TEXTURE_2D);
     GLuint  texture;
     texture =  LoadTexture(FName );
     glBindTexture (GL_TEXTURE_2D, texture);

     drawSquare();

}

Output from the software

2 个答案:

答案 0 :(得分:1)

问题得到解决,因为BMp图像以32位深度保存。  在以24位深度保存图像后,opengl正确映射了它

enter image description here

答案 1 :(得分:1)

你还有一个问题,那就是使用GL_CLAMP并使用纹理坐标0.01.0,这些纹理超出了纹理。它会在你的方块边缘产生1个纹素扭曲。如果您需要完美的映射,那么有两种可能的解决方案:

  1. 将纹理坐标移动一半像素

    如果纹理的大小为sz(以像素为单位),则只需将坐标更改为:

    0.0 + (0.5/sz)
    1.0 - (0.5/sz)
    
  2. 使用换行分机GL_CLAMP_TO_EDGE

    所以只需将GL_CLAMP更改为GL_CLAMP_TO_EDGE,然后像现在一样使用0.0,1.0。如果您没有定义GL_CLAMP_TO_EDGE add:

    #ifndef GL_CLAMP_TO_EDGE
    #define GL_CLAMP_TO_EDGE 0x812F
    #endif
    

    注意你的gfx驱动程序必须支持这个扩展(但我​​不知道任何没有这个的gfx卡)

相关问题