Skip to content

Instantly share code, notes, and snippets.

@mrandri19
Created August 20, 2019 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrandri19/fe5dc2709d761568d749f8125d0f4490 to your computer and use it in GitHub Desktop.
Save mrandri19/fe5dc2709d761568d749f8125d0f4490 to your computer and use it in GitHub Desktop.
main.c: Modern text rendering with Linux: Antialiasing
#include <stdio.h>
#include <freetype2/ft2build.h>
#include FT_FREETYPE_H
#include FT_LCD_FILTER_H
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "./stb_image_write.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_Library_SetLcdFilter(ft, FT_LCD_FILTER_DEFAULT);
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_LCD;
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;
unsigned char* data =
malloc(bitmap.width * bitmap.rows * sizeof(unsigned char*));
for (size_t i = 0; i < bitmap.rows; i++) {
for (size_t j = 0; j < bitmap.width; j++) {
data[i * bitmap.width + j] = bitmap.buffer[i * bitmap.pitch + j];
}
}
stbi_write_jpg("image.jpg", bitmap.width / 3, bitmap.rows, 3, data, 100);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment