一.想象一个文字的显示过程
1.给定一个文字则可以确定它的编码值(一般为unicode)
2.根据编码值从字体文件中(通过索引charmaps)找到对应的glyph(包含可以绘制出文字的关键点,相对位置等内容)
3.设置字体大小
4.用某些函数把glyph中的关键点缩放为设置的字体大小
5.将glyph转换为位图点阵
6.在lcd上显示出来
二.程序该如何实现
官网教程
https://freetype.org/freetype2/docs/tutorial/step1.html
代码设想
1.初始化库 FT_Init_FreeType
2.加载字体Face(一个结构体,包含了字体的各种属性和信息) FT_New_Face
3.访问这个Face结构体确定其中所包含的信息例如支持的字符数量等
4设置字体大小 FT_Set_Char_Size FT_Set_Char_Size或FT_Set_Pixel_Sizes
5.根据字符编码值加载glyph
(1)选择charmap,因为它可能支持多种编码方式,不选择默认通过unicode码索引
FT_Select_Charmap(face, /* target face object */ FT_ENCODING_BIG5 ) /* encoding *
(2)根据索引找到glyph
glyph_index = FT_Get_Char_Index( face, charcode )
(3)取出glyph
FT_Load_Glyph(face, /* handle to face object */ glyph_index, /* glyph index */ load_flags ) /* load flags, see below */
(4) 转为位图
FT_Render_Glyph( face->glyph, /* glyph slot */ render_mode ) /* render mode */
6.变化(移动,旋转)
FT_Set_Transform( face, /* target face object */ &matrix, /* pointer to 2x2 matrix */ &delta ); /* pointer to 2d vector */
三.代码详解
首先看主函数,定义了一些变量。
int main( int argc,char** argv )
{
FT_Library library;
FT_Face face;
FT_GlyphSlot slot;
FT_Matrix matrix; /* transformation matrix */
FT_Vector pen; /* untransformed origin */
FT_Error error;
char* filename;
char* text;
double angle;
int target_height;
int n, num_chars;
这里写明程序用法,确保用户在运行程序时提供了正确的参数数量。如果命令行参数不为3,则使用fprintf函数向标准错误流(stderr)输出一条错误信息并调用exit函数,退出并返回1(非零值),表示程序异常终止。
输出到标准错误流的主要目的是将错误信息单独发送到一个与标准输出流 (stdout) 分开的流,它能够使错误信息在程序的各个方面更容易被注意到和处理。
if ( argc != 3 )
{
fprintf ( stderr, "usage: %s font sample-text\n", argv[0] );
exit( 1 );
}
这里对所需变量赋值,以下是对每一行代码的解释:
filename = argv[1]
这行代码将命令行参数中的第一个参数赋值给filename
变量,用于指定文件名text = argv[2]
这行代码将命令行参数中的第二个参数赋值给text
变量,用于指定程序要处理的文本内容num_chars = strlen(text)
这行代码计算text
变量中字符串的字符数angle = (0.0 / 360) * 3.14159 * 2
这行代码计算一个角度的值,并将结果赋值给angle