OpenGL第十一节:拉伸和过滤

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 );//解除绑定
    }
}

 

posted @ 2017-11-28 16:02  yongfengnice  阅读(333)  评论(0编辑  收藏  举报