最简单的调用freetype库实现在控制台输出文字显示

 

#include <ft2build.h>
#include FT_FREETYPE_H
#include <freetype/freetype.h>
#include <freetype/ftglyph.h>

int main() {
    FT_Library    pFTLib         =  NULL;
    FT_Face        pFTFace         =  NULL;
    FT_Error    error         =   0 ;
    FT_Matrix     matrix;
    FT_Vector     pen;

    pen.x = 10;
    pen.y = 10;
    double angle = (25.0f / 360.0f ) * 3.14159 * 2; /* 旋转25度 */
    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 );



    //Init FreeType Lib to manage memory
    error  =  FT_Init_FreeType( &pFTLib);
    if (error) {
        pFTLib  =   0 ;
        printf( " There is some error when Init Library " );
        return   - 1 ;
    }
    //create font face from font file
    error  =  FT_New_Face(pFTLib,  "FreeMono.ttf" ,  0 ,  & pFTFace);
    if ( ! error) {

        FT_Set_Char_Size(pFTFace,  16 << 6 ,  16 << 6 ,  300 ,  300 );
        FT_Glyph    glyph;
        //  load glyph 'C'
        FT_Load_Glyph(pFTFace, FT_Get_Char_Index(pFTFace,  67 ), FT_LOAD_DEFAULT);
        error  =  FT_Get_Glyph(pFTFace -> glyph,  & glyph);

        FT_Glyph_Transform(glyph, &matrix, 0);
        if ( ! error) {
            //  convert glyph to bitmap with 256 gray
            FT_Glyph_To_Bitmap( & glyph, ft_render_mode_normal,  0 ,  1 );
            FT_BitmapGlyph    bitmap_glyph  =  (FT_BitmapGlyph)glyph;
            FT_Bitmap bitmap  =  bitmap_glyph -> bitmap;
            for ( int  i = 0 ; i < bitmap.rows;  ++ i) {
                for ( int  j = 0 ; j < bitmap.width;  ++ j) {
                    //  if it has gray>0 we set show it as 1, o otherwise
                    //printf( " %d " , bitmap.buffer[i * bitmap.width + j] ? 1 : 0 );
                    if(0 == bitmap.buffer[i * bitmap.width + j]){
                        printf( " %s ", ".");
                    }else if(bitmap.buffer[i * bitmap.width + j] <80){
                        printf( " %s ", "o");
                    }else if(bitmap.buffer[i * bitmap.width + j] <160){
                        printf( " %s ", "a");
                    }else {
                        printf( " %s ", "&");
                    }
                }
                printf( " \n " );
            }
            //  free glyph
            FT_Done_Glyph(glyph);
            glyph  =  NULL;
        }
        //  free face
        FT_Done_Face(pFTFace);
        pFTFace  =  NULL;
    }
    //  free FreeType Lib
    FT_Done_FreeType(pFTLib);
    pFTLib  =  NULL;
}

 

posted @ 2021-01-12 11:27  ziwuxian  阅读(423)  评论(0编辑  收藏  举报