1. 程式人生 > >OpenGL第十一節:拉伸和過濾

OpenGL第十一節:拉伸和過濾

bind wap fromfile 坐標 .cpp mfile identity get ott

LTexture.h
void render( GLfloat x, GLfloat y, LFRect* clip = NULL, LFRect* stretch = NULL );

LTexture.cpp

void LTexture::render( GLfloat x, GLfloat y, LFRect* clip, LFRect* stretch )
{
  if( mTextureID != 0 )
  {
    glLoadIdentity();//移除之前的變換

    GLfloat texTop = 0.f;//紋理坐標
    GLfloat texBottom = (GLfloat)mImageHeight / (GLfloat)mTextureHeight;
    GLfloat texLeft = 0.f;
    GLfloat texRight = (GLfloat)mImageWidth / (GLfloat)mTextureWidth;

    GLfloat quadWidth = mImageWidth;
    GLfloat quadHeight = mImageHeight;

    if( clip != NULL )//如果裁剪
    {
      texLeft = clip->x / mTextureWidth;
      texRight = ( clip->x + clip->w ) / mTextureWidth;
      texTop = clip->y / mTextureHeight;
      texBottom = ( clip->y + clip->h ) / mTextureHeight;

      quadWidth = clip->w;
      quadHeight = clip->h;
    }

    if( stretch != NULL )//如果拉伸
    {
      quadWidth = stretch->w;
      quadHeight = stretch->h;
    }

    glTranslatef( x, y, 0.f );//移動

    glBindTexture( GL_TEXTURE_2D, mTextureID );//綁定

    glBegin( GL_QUADS );//繪制
      glTexCoord2f( texLeft, texTop ); glVertex2f( 0.f, 0.f );
      glTexCoord2f( texRight, texTop ); glVertex2f( quadWidth, 0.f );
      glTexCoord2f( texRight, texBottom ); glVertex2f( quadWidth, quadHeight );
      glTexCoord2f( texLeft, texBottom ); glVertex2f( 0.f, quadHeight );
    glEnd();
  }
}

LUtil.cpp
LTexture gStretchedTexture;
LFRect gStretchRect = { 0.f, 0.f, SCREEN_WIDTH, SCREEN_HEIGHT };
GLenum gFiltering = GL_LINEAR;//紋理過濾

bool loadMedia()
{
  if( !gStretchedTexture.loadTextureFromFile( "mini_opengl.png" ) )
  {
    printf( "Unable to load mini texture!\n" );
    return false;
  }

  return true;
}

void render()
{
  glClear( GL_COLOR_BUFFER_BIT );

  gStretchedTexture.render( 0.f, 0.f, NULL, &gStretchRect );

  glutSwapBuffers();
}

void handleKeys( unsigned char key, int x, int y )
{
  if( key == ‘q‘ )
  {
    glBindTexture( GL_TEXTURE_2D, gStretchedTexture.getTextureID() );//綁定,然後修改

    if( gFiltering != GL_LINEAR )
    {
      glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );//線性拉伸
      glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

      gFiltering = GL_LINEAR;
    }
    else
    {
      glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );//附近拉伸
      glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );

      gFiltering = GL_NEAREST;
    }

    glBindTexture( GL_TEXTURE_2D, NULL );//解除綁定
    }
}

OpenGL第十一節:拉伸和過濾