FreeType2使用指南

597 阅读2分钟
void main(){


    FT_Library _FTlibrary;
    FT_Init_FreeType(&_FTlibrary);
    FT_New_Face(this->getFTLibrary(), filePath, 0, &face);// 加载字体
    FT_Face face;
    FT_Set_Char_Size(face, 0, 16 * 64, 300, 300);    // 设置字符大小
    FT_Error error;
    FT_UInt index = FT_Get_Char_Index(face, 'A'); // 获取字符的索引
    error = FT_Load_Glyph(face, index, FT_LOAD_DEFAULT); // 渲染字符位图
    FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
    FT_Bitmap bitmap = face->glyph->bitmap; // 渲染结果存储在bitmap中
    int width = bitmap.width;
    int height = bitmap.rows;
    
    unsigned char* buffer = bitmap.buffer; // need delete
    
    FT_Done_FreeType(&_FTlibrary);
}

FT_Init_FreeType: 函数对库进行初始化

FT_Init_FreeType 函数的原型如下:

FT_Error FT_Init_FreeType(FT_Library* alibrary);

alibrary 参数是一个指向 FT_Library 结构体指针的指针,用于存储初始化后的库对象。

如果初始化成功,则返回值为 FT_Err_Ok,否则返回相应的错误代码。

FT_New_Face: 函数创建字体对象

FT_New_Face 函数的原型如下:

FT_Error FT_New_Face(
    FT_Library library, 
    const char* filepathname, 
    FT_Long face_index, 
    FT_Face* aface
);
  • library 参数是一个已初始化的库对象;
  • filepathname 是包含字体文件路径和名称的 C 字符串;
  • face_index 是字体库中要加载的字体索引(通常为 0);
  • aface 是一个指向 FT_Face 结构体指针的指针,用于存储创建后的字体对象。

如果初始化成功,则返回值为 FT_Err_Ok,否则返回相应的错误代码。

调用 FT_New_Face 函数后,可以通过访问 FT_Face 结构体中的字段来获取字体信息和相关数据,例如字体名称、字符映射表、字形轮廓等。具体操作方法需要结合相应的文档和示例代码。

FT_Set_Char_Size: 设置字符大小

FT_Set_Char_Size 函数的原型如下:

FT_Error FT_Set_Char_Size(
    FT_Face face, 
    FT_F26Dot6 char_width, 
    FT_F26Dot6 char_height, 
    FT_UInt horz_resolution, 
    FT_UInt vert_resolution
);
  • face 参数是一个已创建的字体对象;
  • char_width 和 char_height 分别表示字符宽度和字符高度,单位是 1/64 像素;
  • horz_resolution 和 vert_resolution 分别表示水平和垂直分辨率,单位是点(1/72 英寸)。

如果设置成功,则返回值为 FT_Err_Ok,否则返回相应的错误代码。

调用 FT_Set_Char_Size 函数后,可以通过 FT_Load_Char 函数加载并渲染指定字符的字形轮廓。

FT_Get_Char_Index: 获取指定字符的索引值

FT_Get_Char_Index 函数的原型如下:

c++Copy Code
FT_UInt FT_Get_Char_Index(FT_Face face, FT_ULong charcode);
  • face 参数是一个已创建的字体对象;
  • charcode 参数是要获取索引值的字符编码。

如果指定字符存在于字体中,则返回该字符的索引值,否则返回 0。

通过 FT_Get_Char_Index 函数获取字符索引后,可以使用 FT_Load_Glyph 加载指定索引对应的字形轮廓并进行渲染。需要注意的是,字符编码和索引值是不同的概念,在使用 FreeType 库进行字形渲染时应当区分开来。

FT_Bitmap

  • rows:位图的行数;

  • width:位图的列数;

  • pitch:位图每行占用的字节数;

  • buffer:指向位图数据的指针;

  • num_grays:灰度级别数;

  • pixel_mode:像素模式(如单通道灰度模式、RGB 模式、BGR 模式等);

  • palette_mode:调色板模式。