嵌入式 用Freetype获取字符位图

来源:互联网 发布:mac os x10.11下载 编辑:程序博客网 时间:2024/06/10 23:42
Freetype是一个操作字体的函数库,它不但可以处理点阵字体,也可以处理多种矢量字体,包括truetype字体,为上层应用程序提供了一个统一的调用接口。Freetype具有良好的可移植性,特别考虑了嵌入式应用环境,字体文件可以在文件系统中,也可以在ROM中,甚至可以用自定义IO函数来访问字体数据。Freetype采用模块化设计,很容易进行扩充和裁减,据说如果只支持truetype,裁减后的二进制文件大小只有25KFreetype是开放源代码的,它采用FreeTypeGPL两种开源协议,可以用于任何商业用途。Freetype的使用相对比较简单,下面将以一个小例子来讲解一下如何使用Freetype的函数来获取字符的位图,该例子是取32* 32大小的位图,注释部分为详细讲解Freetype的函数,因此字可能会比较多。不多说了,来看例子吧:

 

#include <stdio.h>

#include <string.h>

#includeFT_FREETYPE_H

 

#define CHARSIZE 32 //字符位图的大小设为32 * 32

 

int GetCharBitmap(intiCharSize, unsigned int uiCharCode);

 

int main(int argc, char**argv)

{

    unsigned int uiCharCode = 0x0061; //字母aucs2编码.

    GetCharBitmap(CHARSIZE, uiCharCode);

    return 0;

}

 

int GetCharBitmap(intiCharSize, unsigned int uiCharCode)

{

    FT_Library ftLibrary;

    FT_Error ftError = FT_Init_FreeType(&ftLibrary);

    if(ftError)

    {

        printf("Init freetype library fail!\n");

        return -1;

    }

 

    FT_Face ftFace;

    ftError = FT_New_Face( ftLibrary, "ukai.ttc", 0, &ftFace );

    if(ftError == FT_Err_Unknown_File_Format)

    {

        printf("Error! Could not support this format!\n");

        return -1;

    }

    else if(ftError)

    {

        printf("Error! Could not open file ukai.ttc!\n");

        return -1;

    }

 

 

ftError =FT_Set_Pixel_Sizes(ftFace, iCharSize, 0);

    if(ftError)

    {

        printf("Set pixel sizes to %d*%d error!\n", iCharSize,iCharSize);

        return -1;

    }

    FT_UInt uiGlyphIndex = FT_Get_Char_Index(ftFace,uiCharCode);

 

    FT_Load_Glyph(ftFace,uiGlyphIndex, FT_LOAD_DEFAULT);

 

 

    FT_Render_Glyph(ftFace->glyph, FT_RENDER_MODE_MONO);


    int iRow = 0, iCol = 0;
    for(iRow = 0; iRow < ftFace->glyph->bitmap.rows;iRow++)
    {
        for(iCol = 0; iCol < ftFace->glyph->bitmap.width;iCol++)
        {
             if((ftFace->glyph->bitmap.buffer[iRow *ftFace->glyph->bitmap.pitch + iCol/8] & (0xC0 >>(iCol % 8))) == 0)
             {
                  printf("_");
             }
   else
            
                  printf("0");

       }

        }

        printf("\n");

    }

    return 0;

}
原创粉丝点击