要使用OpenGL、SDL和C++绘制文本,您需要使用一种名为FreeType的库。FreeType是一个用于处理字体文件的常用库,可以轻松地将字体转换为可在OpenGL和SDL中使用的文本纹理。以下是一个简单的示例,说明如何使用这些库绘制文本:
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_opengl.h>
#include <freetype2/ft2build.h>
#include FT_FREETYPE_H
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_Window* window = SDL_CreateWindow("Text Rendering", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
SDL_GLContext glContext = SDL_GL_CreateContext(window);
GLenum status = glewInit();
if (status != GLEW_OK) {
printf("GLEW initialization failed\n");
}
FT_Library ft;
if (FT_Init_FreeType(&ft)) {
std::cout << "Error: Could not initialize FreeType library"<< std::endl;
}
FT_Face face;
if (FT_New_Face(ft, "path/to/font/file.ttf", 0, &face)) {
std::cout << "Error: Failed to load font"<< std::endl;
}
FT_Set_Pixel_Sizes(face, 0, 48);
GLuint load_texture(FT_Face face) {
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, face->glyph->bitmap.width, face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
return texture;
}
void render_text(std::string text, GLuint texture, FT_Face face) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindTexture(GL_TEXTURE_2D, texture);
glColor3f(1.0f, 1.0f, 1.0f);
float x = 0.0f;
float y = 0.0f;
for (char c : text) {
if (c == '\n') {
y -= 1.0f;
x = 0.0f;
} else {
FT_Load_Char(face, c, FT_LOAD_RENDER);
GLuint glyph_texture = load_texture(face);
float x2 = x + face->glyph->bitmap_left;
float y2 = y - face->glyph->bitmap_top;
float w = face->glyph->bitmap.width;
float h = face->glyph->bitmap.rows;
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(x2, y2);
glTexCoord2f(1, 0); glVertex2f(x2 + w, y2);
glTexCoord2f(1, 1); glVertex2f(x2 + w, y2 + h);
glTexCoord2f(0, 1); glVertex2f(x2, y2 + h);
glEnd();
x += face->glyph->advance.x >> 6;
y += face->glyph->advance.y >> 6;
}
}
glDisable(GL_BLEND);
}
bool running = true;
SDL_Event event;
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
}
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
render_text("Hello, World!", load_texture(face), face);
SDL_GL_SwapWindow(window);
}
领取专属 10元无门槛券
手把手带您无忧上云