ZBLOG

使用opengl把纹理缩放成1/2的例子

以下是使用OpenGL将纹理缩放为1/2的简单示例代码:

#include <GL/glut.h>
#include <iostream>

// 原始纹理宽度和高度
int textureWidth = 512;
int textureHeight = 512;

// 缩放后的纹理宽度和高度
int scaledTextureWidth = textureWidth / 2;
int scaledTextureHeight = textureHeight / 2;

GLuint texture; // 纹理ID

// 加载纹理函数
void loadTexture() {
    // 在这里加载并绑定你的纹理,可以使用SOIL、FreeImage或其他库来加载图片并生成纹理
    // 确保设置正确的纹理参数(例如过滤方式、重复模式等)
}

// 初始化函数
void init() {
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // 设置清屏颜色为黑色
    glEnable(GL_TEXTURE_2D); // 启用2D纹理映射

    loadTexture(); // 加载纹理数据

    glViewport(0, 0, scaledTextureWidth, scaledTextureHeight); // 设置视口大小为缩放后的纹理大小

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, scaledTextureWidth, 0.0, scaledTextureHeight);

    glMatrixMode(GL_MODELVIEW);
}

// 渲染函数
void render() {
    glClear(GL_COLOR_BUFFER_BIT);

    glBindTexture(GL_TEXTURE_2D, texture); // 绑定纹理

    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 0.0f); // 左下角
    glTexCoord2f(1.0f, 0.0f); glVertex2f(scaledTextureWidth, 0.0f); // 右下角
    glTexCoord2f(1.0f, 1.0f); glVertex2f(scaledTextureWidth, scaledTextureHeight); // 右上角
    glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, scaledTextureHeight); // 左上角
    glEnd();

    glutSwapBuffers();
}

// 窗口大小变化回调函数
void reshape(int width, int height) {
    glViewport(0, 0, width, height);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, width, 0.0, height);

    glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(scaledTextureWidth, scaledTextureHeight);
    
     // 根据实际情况创建窗口并设置标题
     glutCreateWindow("Scaled Texture");

     init();

     glutDisplayFunc(render);
     glutReshapeFunc(reshape);

     glutMainLoop();

     return 0;
}

在这个示例中,你需要先加载原始纹理数据,并将其绑定到OpenGL的纹理对象。然后,在渲染函数中使用glBeginglEnd来定义一个矩形,并为每个顶点设置纹理坐标。通过调用glTexCoord2f函数设置纹理坐标,然后调用glVertex2f函数来指定对应的顶点位置。

init函数中,你需要根据缩放后的纹理大小重新设置视口和投影矩阵。

请注意,以上代码仅是一个简单示例,实际使用时可能需要更多的OpenGL和图像处理知识。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=8121

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?