#include <cstdio> #include <cstdlib> #include <cmath> // freetype2 头文件 #include <ft2build.h> #include FT_FREETYPE_H // for freetype support #include FT_GLYPH_H // 最终文本内容存放的内存区域 #define WIDTH 640 #define HEIGHT 480 unsigned char image[HEIGHT][WIDTH]; /* 将freetype2渲染出的字符信息拷贝到文本内存 */ void draw_bitmap( FT_Bitmap* bitmap, FT_Int x, FT_Int y) { FT_Int i, j, p, q; FT_Int x_max = x + bitmap->width; FT_Int y_max = y + bitmap->rows; for ( i = x, p = 0; i < x_max; i++, p++ ) { for ( j = y, q = 0; j < y_max; j++, q++ ) { if ( i >= WIDTH || j >= HEIGHT ) continue; image[j][i] |= bitmap->buffer[q * bitmap->width + p]; } } } // 辅助函数,用于以文本图形式,显示最终渲染的图片 void show_image( void ) { FILE* fp = fopen( "C://textout.txt", "w+" ); int i, j; for ( i = 0; i < HEIGHT; i++ ) { for ( j = 0; j < WIDTH; j++ ) fprintf(fp, "%c", image[i][j] == 0 ? ' ' : image[i][j] < 128 ? '+' : '*' ); fprintf( fp, "/r/n" ); } fclose(fp); } int main( int argc, char** argv ) { char text[] = "freetype"; FT_Library library; // Step1: create library FT_Error error = FT_Init_FreeType( &library ); if( error ) { printf( " initial freetype failed./n" ); goto end; } // Step2: load font face FT_Face face; error = FT_New_Face( library, "C://test.TTF", 0, &face ); if( error == FT_Err_Unknown_File_Format ) { printf( " unknown font format./n" ); goto end; } else if( error ) { printf( " error to load font./n" ); goto end; } // Step3: set char size /* use 50pt at 100dpi */ error = FT_Set_Char_Size( face, 50 * 64, 0, 100, 0 ); /* set character size */ // Step4: render characters one by one FT_GlyphSlot slot = face->glyph; FT_Matrix matrix; /* transformation matrix */ /* set up matrix */ const float angle = 3.1415956f/4.0f; matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L ); matrix.xy = (FT_Fixed)(-sin( angle ) * 0x10000L ); matrix.yx = (FT_Fixed)( sin( angle ) * 0x10000L ); matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L ); FT_Vector pen; /* untransformed origin */ /* the pen position in 26.6 cartesian space coordinates; */ /* start at (300,200) relative to the upper left corner */ pen.x = 300* 64; pen.y = ( HEIGHT - 200 ) * 64; int num_chars = strlen(text); for ( int n = 0; n < num_chars; n++ ) { /* set transformation */ FT_Set_Transform( face, &matrix, &pen ); /* load glyph image into the slot (erase previous one) */ error = FT_Load_Char( face, text[n], FT_LOAD_RENDER ); if ( error ) continue; /* ignore errors */ /* now, draw to our target surface (convert position) */ draw_bitmap( &slot->bitmap, slot->bitmap_left, HEIGHT - slot->bitmap_top ); /* increment pen position */ pen.x += slot->advance.x; pen.y += slot->advance.y; } show_image(); // Step5: close resources FT_Done_Face( face ); FT_Done_FreeType( library ); end:getchar(); return 0; }