1. #include<stdio.h>
    2. #include <ft2build.h>
    3. #include FT_FREETYPE_H
    4. #define CHARSIZE 32 // 字符位图的大小设为32 * 32
    5. int GetCharBitmap(int iCharSize, unsigned int uiCharCode);
    6. int main()
    7. {
    8. //wchar_t ch = 'b'; //英文字符
    9. wchar_t ch = L'总'; //中文字符
    10. //wchar_t ch = '你';
    11. /* 中文字符必须要加L,不然得不到字符索引FT_Get_Char_Index()返回0
    12. * FreeType默认为unicode的字符表
    13. * L将ANSI字符串转换成unicode的字符串
    14. *
    15. */
    16. GetCharBitmap(CHARSIZE, ch);
    17. return 0;
    18. }
    19. int GetCharBitmap(int iCharSize, unsigned int uiCharCode)
    20. {
    21. // - 初始化FreeType对象
    22. FT_Library ftLibrary;
    23. FT_Error ftError = FT_Init_FreeType(&ftLibrary);
    24. if(ftError)
    25. {
    26. printf("Init freetype library fail!/n");
    27. return -1;
    28. }
    29. // - 从字体文件中装载一个Face
    30. FT_Face ftFace;
    31. ftError = FT_New_Face(ftLibrary,
    32. "C:\\WINDOWS\\Fonts\\simhei.ttf", //黑体中文字库
    33. 0,
    34. &ftFace);
    35. if(ftError == FT_Err_Unknown_File_Format)
    36. {
    37. // 表示可以打开和读此文件,但不支持此字体格式
    38. printf("Error! Could not support this format!/n");
    39. return -1;
    40. }
    41. else if(ftError) // 其他错误
    42. {
    43. printf("Error! Could not open file ukai.ttc!/n");
    44. return -1;
    45. }
    46. // - 设置
    47. ftError = FT_Set_Pixel_Sizes(ftFace, iCharSize, 0);
    48. if(ftError)
    49. {
    50. printf("Set pixel sizes to %d*%d error!/n", iCharSize, iCharSize);
    51. return -1;
    52. }
    53. // - 得到字符码的字形索引
    54. FT_UInt uiGlyphIndex = FT_Get_Char_Index(ftFace, uiCharCode);
    55. if(uiGlyphIndex<=0)
    56. {
    57. printf("未找到该字符的索引");
    58. return -1;
    59. }
    60. FT_Load_Glyph(ftFace, uiGlyphIndex, FT_LOAD_DEFAULT);
    61. // - 生成位图
    62. if(ftFace->glyph->format != FT_GLYPH_FORMAT_BITMAP)
    63. {
    64. FT_Render_Glyph(ftFace->glyph, FT_RENDER_MODE_MONO);
    65. }
    66. int iRow = 0, iCol = 0;
    67. for(iRow = 0; iRow < ftFace->glyph->bitmap.rows; iRow++)
    68. {
    69. for(iCol = 0; iCol < ftFace->glyph->bitmap.width; iCol++)
    70. {
    71. if((ftFace->glyph->bitmap.buffer[iRow * ftFace->glyph->bitmap.pitch + iCol / 8] & (0xC0 >> (iCol % 8))) == 0)
    72. {
    73. printf("1");
    74. }
    75. else
    76. {
    77. printf("0");
    78. }
    79. }
    80. printf("\n");
    81. }
    82. return 0;
    83. }