以下是使用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的纹理对象。然后,在渲染函数中使用glBegin
和glEnd
来定义一个矩形,并为每个顶点设置纹理坐标。通过调用glTexCoord2f
函数设置纹理坐标,然后调用glVertex2f
函数来指定对应的顶点位置。
在init
函数中,你需要根据缩放后的纹理大小重新设置视口和投影矩阵。
请注意,以上代码仅是一个简单示例,实际使用时可能需要更多的OpenGL和图像处理知识。
内容由零声教学AI助手提供,问题来源于学员提问