freetype_2_在PC上使用freetype显示任意字符
在上一篇文章中已经实现了PC上显示英文字符和阿拉伯数字,这一篇文章实现PC上显示中文等其他字符(当然,英文字符和阿拉伯数字同样可以显示,其他的特殊字体需要相应字体文件支持才可以显示)
贴出需要修改的代码
for ( 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,
target_height - slot->bitmap_top );
/* increment pen position */
pen.x += slot->advance.x;
pen.y += slot->advance.y;
}
将num_chars改为4(这里我们只显示4个字符),将text改为str
并且在前面作出如下定义:
int str[] = {0x8fd9,0x662f,0x32,0x34};
修改完毕,重新编译运行 ./build 字体文件 字符串 ,便会显示 “这是24” 的字样
至此已经成功显示了中文字符
如果我们使用,char类型(如char* = “这是24”;),这时会出现一个问题,中文占两字节,而英文占一字节,这样处理不同字长的字符时,需要分类处理,比较麻烦,所以引入了宽字符概念
不管是什么字符,都使用宽字符类型来定义,处理方便了,但是宽字符的字长是4字节,对于字长小的字符来说,存储空间消耗就变大了
使用宽字符相关库时,包含头文件:
#include <wchar.h>
宽字符定义
wchar_t *str = L"这是2g4";
取字长
num = wcsten(str);
使用宽字符的库,修改下面代码
for ( n = 0; n < 4; n++ )
{
/* set transformation */
FT_Set_Transform( face, &matrix, &pen );
/* load glyph image into the slot (erase previous one) */
error = FT_Load_Char( face, str[n], FT_LOAD_RENDER );
if ( error )
continue; /* ignore errors */
/* now, draw to our target surface (convert position) */
draw_bitmap( &slot->bitmap,
slot->bitmap_left,
target_height - slot->bitmap_top );
/* increment pen position */
pen.x += slot->advance.x;
pen.y += slot->advance.y;
}
1、将4改为num,并且在前面定义num
2、将变量str类型改为wchar_t *类型
3、引入头文件wchar.h
重新编译,运行 ./build 字体文件 字符串