Skip to content

Instantly share code, notes, and snippets.

@mrandri19 mrandri19/main.c
Last active Feb 26, 2020

Embed
What would you like to do?
main.c: Modern text rendering with Linux: Part 1
#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;
}
@JohnCoconut

This comment has been minimized.

Copy link

JohnCoconut commented Jul 24, 2019

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?

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");
}
@Oleh-Kravchenko

This comment has been minimized.

Copy link

Oleh-Kravchenko commented Aug 15, 2019

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
You can’t perform that action at this time.