- 1 year ago
Displaying text and integer values on window-OpenGL
Comment
1 / 1
To display text and integer values on a window using OpenGL, you can utilize a combination of OpenGL functions and library dependencies. Here's an example that demonstrates how to achieve this using the FreeGLUT library for window management and the FreeType library for text rendering:
c#include <GL/glut.h>
#include <ft2build.h>
#include FT_FREETYPE_H
FT_Library ft;
FT_Face face;
void renderText(const char* text, float x, float y, int fontSize) {
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, glutGet(GLUT_WINDOW_WIDTH), 0, glutGet(GLUT_WINDOW_HEIGHT), -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glRasterPos2f(x, y);
FT_Set_Pixel_Sizes(face, 0, fontSize);
for (const char* p = text; *p; p++) {
if (FT_Load_Char(face, *p, FT_LOAD_RENDER))
continue;
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);
glPushMatrix();
glTranslatef(face->glyph->bitmap_left, face->glyph->bitmap_top - face->glyph->bitmap.rows, 0.0f);
glScaled(1.0f, -1.0f, 1.0f);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f(0, 0);
glTexCoord2f(0, 1);
glVertex2f(0, face->glyph->bitmap.rows);
glTexCoord2f(1, 1);
glVertex2f(face->glyph->bitmap.width, face->glyph->bitmap.rows);
glTexCoord2f(1, 0);
glVertex2f(face->glyph->bitmap.width, 0);
glEnd();
glPopMatrix();
glTranslatef(face->glyph->advance.x >> 6, 0.0f, 0.0f);
}
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
void display() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 1.0f, 1.0f);
renderText("Hello, World!", 50.0f, 50.0f, 24);
int value = 42;
char valueText[10];
snprintf(valueText, 10, "%d", value);
renderText(valueText, 50.0f, 100.0f, 18);
glutSwapBuffers();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL Text Rendering");
FT_Init_FreeType(&ft);
FT_New_Face(ft, "path_to_font.ttf", 0, &face);
glutDisplayFunc(display);
glutMainLoop();
FT_Done_Face(face);
FT_Done_FreeType(ft);
return 0;
}
To compile and run this code, make sure you have the FreeGLUT and FreeType libraries installed and linked correctly. Replace `"path_to_font