使用Freetype库的步骤
1. 初始化
/*
library:指向FT_Library类型的指针,用于接收初始化后的FreeType库对象
*/
FT_Error FT_Init_FreeType(FT_Library *library);
2. 加载字体Face
/*
library:一个已初始化的 FreeType 库对象,是对 FreeType 运行时环境的引用;
filepathname:一个指向字体文件路径名的字符串,表示要加载的字体文件;
face_index:字体文件中的字体索引,用于指定要加载的具体字体,一些字体文件可能包含多个字体,每个字体都有自己的索引;
aface:指针类型,用于接收创建的新字体对象;
*/
FT_Error FT_New_Face(FT_Library library, const char* filepathname, FT_Long face_index, FT_Face* aface);
3. 设置字体大小
/*
face:一个已加载的字体对象;
pixel_width:期望的字体宽度(以像素为单位);
pixel_height:期望的字体高度(以像素为单位);
*/
FT_Error FT_Set_Pixel_Sizes(FT_Face face, FT_UInt pixel_width, FT_UInt pixel_height);
4. 确定变换坐标
/*
face:要设置变换矩阵的FT_Face结构体指针;
matrix:指向FT_Matrix结构体的指针,表示欲应用的变换矩阵。FT_Matrix结构体包含了3x3的矩阵元素,用于表示缩放、旋转和平移的变换;
delta:指向FT_Vector结构体的指针,表示欲应用的平移量。FT_Vector结构体包含了横向和纵向的平移值
*/
void FT_Set_Transform(FT_Face face, const FT_Matrix* matrix, const FT_Vector* delta);
5. 获取字符的位图
/*
face: 需要加载字符的字体面对象;
char_code: 要加载的字符代码,可以使用字符的 Unicode 编码或字符的 ASCII 值;
load_flags: 加载字形数据时的选项标志, FT_LOAD_RENDER: 加载并渲染字形位图;
*/
FT_Error FT_Load_Char(FT_Face face, FT_ULong char_code, FT_Int32 load_flags);
6. 示例
#include <math.h>
int main(int argc, char *argv[])
{
FT_Library library;
FT_Face face;
int error;
FT_Matrix matrix;
FT_Vector pen;
double angle = 1.570795;
FT_GlyphSlot slot;
int font_size = 24;
int lcd_x = 200, lcd_y = 100;
wchar_t *chinese_str = L"繁";
//
error = FT_Init_FreeType(&library);
if(error){
printf("error FT_Init_FreeType\n");
return -1;
}
error = FT_New_Face(library, argv[1], 0, &face);
if(error){
printf("error FT_New_Face\n");
return -1;
}
//
FT_Set_Pixel_Sizes(face, font_size, 0);
//
pen.x = 0;
pen.y = 0;
matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L );
matrix.xy = (FT_Fixed)(-sin( angle ) * 0x10000L );
matrix.yx = (FT_Fixed)( sin( angle ) * 0x10000L );
matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L );
FT_Set_Transform(face, &matrix, &pen);
//
error = FT_Load_Char( face, chinese_str[0], FT_LOAD_RENDER );
if(error){
printf("error FT_Load_Char\n");
return -1;
}
//
slot = face->glyph;
draw_bitmap(&slot->bitmap, lcd_x, lcd_y);
}
7. 注意事项
编译时需要链接相关的库
book@100ask:~/linux_test/freetype$ ${CROSS_COMPILE}gcc -o angle freetype_show_angle.c -lm -lfreetype