OpenGL第十一节:拉伸和过滤

Posted yongfengnice

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 );//解除绑定
    }
}

 

以上是关于OpenGL第十一节:拉伸和过滤的主要内容,如果未能解决你的问题,请参考以下文章

GLUT OpenGL Cube 拉伸错误

opengl GPU 纹理加速优化

OpenGL 防止在调整窗口大小时拉伸

C#第十一节课

第十一节:视图和临时表

python学习笔记第十一节(迭代和其他)