下面是一个使用GLFW库将纹理缩放为1/2并显示的例子,基于OpenGL:
#include <iostream>
#include <GLFW/glfw3.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
// 窗口大小
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
int main()
{
// 初始化GLFW
if (!glfwInit())
{
std::cout << "Failed to initialize GLFW" << std::endl;
return -1;
}
// 创建窗口和上下文
GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Texture Scaling", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// 设置视口大小回调函数
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// 加载图像数据
int imageWidth, imageHeight, nrChannels;
unsigned char* imageData = stbi_load("texture.jpg", &imageWidth, &imageHeight, &nrChannels, 0);
if (imageData == nullptr)
{
std::cout << "Failed to load texture" << std::endl;
glfwTerminate();
return -1;
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // 对齐字节
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
if (nrChannels == 3)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imageWidth / 2, imageHeight / 2,
0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
}
else if (nrChannels == 4)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, imageWidth / 2,
imageHeight / 2,
0, GL_RGBA,GL_UNSIGNED_BYTE,imageData);
}
else
{
std::cout << "Unsupported format" << std::endl;
stbi_image_free(imageData);
glfwTerminate();
return -1;
}
// 渲染循环
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
// 绘制矩形,并使用纹理进行填充
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f,-1.0f);
glTexCoord2f(1.0f ,1.0f); glVertex2f(1.0f,-1.0f);
glTexCoord2f(1.0f , 0.5f); glVertex2f(1.0f , 1.5 );
glTexCoord2f(0.0 ,-imageHeight/float(imageHeight * 4)); glVertex2f(-1.0 , 1.5 );
glEnd();
// 交换缓冲区和获取输入
glfwSwapBuffers(window);
glfwPollEvents();
}
// 清理资源
stbi_image_free(imageData);
glfwTerminate();
return 0;
}
在上述代码中,我们使用了glfw创建了一个窗口,加载并绑定了纹理数据,并通过GL_QUADS绘制一个矩形,并使用纹理进行填充。其中纹理的尺寸被缩放为原来的一半,即imageWidth / 2 和 imageHeight / 2。
请确保在运行代码之前将”texture.jpg”替换为你自己的纹理图片路径,并且安装并配置好GLFW库以及stb_image库。
内容由零声教学AI助手提供,问题来源于学员提问