Last active
July 3, 2022 19:30
-
-
Save mrandri19/245237a6bde246f119ab2b6245e540ba to your computer and use it in GitHub Desktop.
main.c: Modern text rendering with Linux: Part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <freetype2/ft2build.h> | |
#include FT_FREETYPE_H | |
int main() { | |
FT_Library ft; | |
FT_Error err = FT_Init_FreeType(&ft); | |
if (err != 0) { | |
printf("Failed to initialize FreeType\n"); | |
exit(EXIT_FAILURE); | |
} | |
FT_Int major, minor, patch; | |
FT_Library_Version(ft, &major, &minor, &patch); | |
printf("FreeType's version is %d.%d.%d\n", major, minor, patch); | |
FT_Face face; | |
err = FT_New_Face(ft, "./UbuntuMono.ttf", 0, &face); | |
if (err != 0) { | |
printf("Failed to load face\n"); | |
exit(EXIT_FAILURE); | |
} | |
err = FT_Set_Pixel_Sizes(face, 0, 32); | |
if (err != 0) { | |
printf("Failed to set pixel size\n"); | |
exit(EXIT_FAILURE); | |
} | |
FT_UInt glyph_index = FT_Get_Char_Index(face, 'a'); | |
FT_Int32 load_flags = FT_LOAD_DEFAULT; | |
err = FT_Load_Glyph(face, glyph_index, load_flags); | |
if (err != 0) { | |
printf("Failed to load glyph\n"); | |
exit(EXIT_FAILURE); | |
} | |
FT_Int32 render_flags = FT_RENDER_MODE_NORMAL; | |
err = FT_Render_Glyph(face->glyph, render_flags); | |
if (err != 0) { | |
printf("Failed to render the glyph\n"); | |
exit(EXIT_FAILURE); | |
} | |
FT_Bitmap bitmap = face->glyph->bitmap; | |
for (size_t i = 0; i < bitmap.rows; i++) { | |
for (size_t j = 0; j < bitmap.width; j++) { | |
unsigned char pixel_brightness = | |
bitmap.buffer[i * bitmap.pitch + j]; | |
if (pixel_brightness > 169) { | |
printf("*"); | |
} else if (pixel_brightness > 84) { | |
printf("."); | |
} else { | |
printf(" "); | |
} | |
} | |
printf("\n"); | |
} | |
return 0; | |
} |
You forget about memory management. Where is memory free?
FT_Done_Glyph()
FT_Done_Face()
FT_Done_Library()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the tutorial. I enjoy going through it.
I have a suggestion. The chain of
face->glyph->bitmap
is hard to read, so why not putting it into a variable, like this?