The FreeType 2 Tutorial

来源:互联网 发布:sql中count 1 编辑:程序博客网 时间:2024/05/17 05:14

原文链接:http://www.freetype.org/freetype2/docs/tutorial/step1.html
翻译人员:gogoliu


英文 中文 FreeType 2 Tutorial

Step 1 — simple glyph loading
© 2003, 2006 David Turner (david@freetype.org)
© 2003, 2006 The FreeType Development Team (www.freetype.org)

FreeType 2 教程

第一步 -- 简易的字形装载
© 2003, 2006 David Turner (david@freetype.org)
© 2003, 2006 FreeType 开发小组 (www.freetype.org)

Introduction 介绍 This is the first section of the FreeType 2 tutorial. It will teach you how to:
  • initialize the library
  • open a font file by creating a new face object
  • select a character size in points or in pixels
  • load a single glyph image and convert it to a bitmap
  • render a very simple string of text
  • render a rotated string of text easily
这是“FreeType2 教程”的第一部分。它将教会你如何:
  • 初始化库
  • 通过创建一个新的 face 对象来打开一个字体文件
  • 以点或者象素的形式选择一个字符大小
  • 装载一个字形(glyph)图像,并把它转换为位图
  • 渲染一个简单的字符串
  • 容易地渲染一个旋转的字符串
1. Header files 1、头文件 The following are instructions required to compile an application that uses the FreeType 2 library. Please read them carefully; we have changed a few things since the last release!
1. Locate the FreeType 2 include directory.
You have to add it to your compilation include path.
Note that on Unix systems, you can now run the freetype-config script with the --cflags option to retrieve the appropriate compilation flags. This script can also be used to check the version of the library that is installed on your system, as well as the required librarian and linker flags.
2. Include the file named ft2build.h.
It contains various macro declarations that are later used to #include the appropriate public FreeType 2 header files.
3. Include the main FreeType 2 API header file.
You should do that using the macro FT_FREETYPE_H, like in the following example:
     #include <ft2build.h>     #include FT_FREETYPE_H
FT_FREETYPE_H is a special macro defined in the file ftheader.h. It contains some installation-specific macros to name other public header files of the FreeType 2 API.
You can read this section of the FreeType 2 API Reference for a complete listing of the header macros.
下面的内容是编译一个使用了FreeType2库的应用程序所需要的指令。请谨慎阅读,自最近一次版本更新后我们已经更改了少许东西。
1. FreeType2 include 目录
你必须把FreeType2头文件的目录添加到编译包含(include)目录中。
注意,现在在Unix系统,你可以运行freetype-config脚本加上--cflags选项来获得正确的编译标记。这个脚本也可以用来检查安装在你系统中的库的版本,以及需要的库和连接标记。
2. 包含名为ft2build.h的文件
Ft2build.h包含了接下来要#include的公共FreeType2头文件的宏声明。
3. 包含主要的FreeType2 API头文件
你要使用FT_FREETYPE_H宏来完成这个工作,就像下面这样:
   #include <ft2build.h>   #include FT_FREETYPE_H
FT_FREETYPE_H是在ftheader.h中定义的一个特别的宏。Ftheader.h包含了一些安装所特定的宏,这些宏指名了FreeType2 API的其他公共头文件。
你可以阅读“FreeType 2 API参考”的这个部分来获得头文件的完整列表。
The use of macros in #include statements is ANSI-compliant. It is used for several reasons:
  • It avoids some painful conflicts with the FreeType 1.x public header files.
  • The macro names are not limited to the DOS 8.3 file naming limit; names like FT_MULTIPLE_MASTERS_H or FT_SFNT_NAMES_H are a lot more readable and explanatory than the real file names ftmm.h and ftsnames.h.
  • It allows special installation tricks that will not be discussed here.
#include语句中宏的用法是服从ANSI的。这有几个原因:
  • 这可以避免一些令人痛苦的与FreeType 1.x公共头文件的冲突。
  • 宏名字不受限于DOS的8.3文件命名限制。象FT_MULTIPLE_MASTERS_H或FT_SFNT_NAMES_H这样的名字比真实的文件名ftmm.h和fsnames.h更具可读性并且更容易理解。
  • 它允许特别的安装技巧,我们不在这里讨论它。
NOTE: Starting with FreeType 2.1.6, the old header file inclusion scheme is no longer supported. This means that you now get an error if you do something like the following:
 #include <freetype/freetype.h> #include <freetype/ftglyph.h> ...
注意:从FreeType 2.1.6开始,旧式的头文件包含模式将不会再被支持。这意味着现在如果你做了象下面那样的事情,你将得到一个错误:
 #include <freetype/freetype.h> #include <freetype/ftglyph.h> ...
2. Initialize the library 2、初始化库 Simply create a variable of type FT_Library named, for example, library, and call the function FT_Init_FreeType as in
 #include <ft2build.h> #include FT_FREETYPE_H  FT_Library library;  ...  error = FT_Init_FreeType( &library ); if ( error ) {   ... an error occurred during library initialization ... }
简单地创建一个FT_Library类型的变量,例如library,然后象下面那样调用函数FT_Init_FreeType:
 #include <ft2build.h> #include FT_FREETYPE_H  FT_Library library;  ...  error = FT_Init_FreeType( &library ); if ( error ) {   ... 在初始化库时发生了一个错误 ... }
This function is in charge of the following:
  • It creates a new instance of the FreeType 2 library, and sets the handle library to it.
  • It loads each module that FreeType knows about in the library. Among others, your new library object is able to handle TrueType, Type 1, CID-keyed & OpenType/CFF fonts gracefully.
这个函数负责下面的事情:
  • 它创建一个FreeType 2库的新实例,并且设置句柄library为它。
  • 它装载库中FreeType所知道的每一个模块。除了别的以外,你新建的library对象可以优雅地处理TrueType, Type 1, CID-keyed 和OpenType/CFF字体。
As you can see, the function returns an error code, like most others in the FreeType API. An error code of 0 always means that the operation was successful; otherwise, the value describes the error, and library is set to NULL. 就像你所看到的,这个函数返回一个错误代码,如同FreeType API的大部分其他函数一样。值为0的错误代码始终意味着操作成功了,否则,返回值指示错误,library设为NULL。 3. Load a font face 3、装载一个字体face a. From a font file a. 从一个字体文件装载 Create a new face object by calling FT_New_Face. A face describes a given typeface and style. For example, ‘Times New Roman Regular’ and ‘Times New Roman Italic’ correspond to two different faces.
 FT_Library library;  /* handle to library */ FT_Face    face;     /* handle to face object */  error = FT_Init_FreeType( &library ); if ( error ) { ... }  error = FT_New_Face( library,                      "/usr/share/fonts/truetype/arial.ttf",                      0,                      &face );  if ( error == FT_Err_Unknown_File_Format ) {   ... the font file could be opened and read, but it appears   ... that its font format is unsupported } else if ( error ) {   ... another error code means that the font file could not    ... be opened or read, or simply that it is broken... }
应用程序通过调用FT_New_Face创建一个新的face对象。一个face对象描述了一个特定的字样和风格。例如,’Times New Roman Regular’和’Times New Roman Italic’对应两个不同的face。
 FT_Library library;  /* 库的句柄 */ FT_Face    face;     /* face对象的句柄 */  error = FT_Init_FreeType( &library ); if ( error ) { ... }  error = FT_New_Face( library,                      "/usr/share/fonts/truetype/arial.ttf",                      0,                      &face );  if ( error == FT_Err_Unknown_File_Format ) {   ... 可以打开和读这个文件,但不支持它的字体格式 } else if ( error ) {   ... 其它的错误码意味着这个字体文件不能打开和读,   ... 或者简单的说它损坏了 ... }
As you can certainly imagine, FT_New_Face opens a font file, then tries to extract one face from it. Its parameters are library A handle to the FreeType library instance where the face object is created. filepathname The font file pathname (a standard C string). face_index Certain font formats allow several font faces to be embedded in a single file.

This index tells which face you want to load. An error will be returned if its value is too large.

Index 0 always work though.

face A pointer to the handle that will be set to describe the new face object.

It is set to NULL in case of error.

就如你所想到的,FT_NEW_Face打开一个字体文件,然后设法从中提取一个face。它的参数为: Library 一个FreeType库实例的句柄,face对象从中建立 Filepathname 字体文件路径名(一个标准的C字符串) Face_index 某些字体格式允许把几个字体face嵌入到同一个文件中。

这个索引指示你想装载的face。

如果这个值太大,函数将会返回一个错误。Index 0总是正确的。

Face 一个指向新建的face对象的指针。

当失败时其值被置为NULL。

To know how many faces a given font file contains, simply load its first face (this is, face_index should be set to zero), then check the value of face->num_faces which indicates how many faces are embedded in the font file. 要知道一个字体文件包含多少个face,只要简单地装载它的第一个face(把face_index设置为0),face->num_faces的值就指示出了有多少个face嵌入在该字体文件中。 b. From memory b. 从内存装载 In the case where you have already loaded the font file into memory, you can similarly create a new face object for it by calling FT_New_Memory_Face as in
 FT_Library library;  /* handle to library */ FT_Face    face;     /* handle to face object */  error = FT_Init_FreeType( &library ); if ( error ) { ... }  error = FT_New_Memory_Face( library,                             buffer,  /* first byte in memory */                             size,    /* size in bytes */                             0,       /* face_index */                             &face ); if ( error ) { ... }
如果你已经把字体文件装载到内存,你可以简单地使用FT_New_Memory_Face为它新建一个face对象,如下所示:
 FT_Library library; /* 库的句柄 */ FT_Face face; /* face对象的句柄 */  error = FT_Init_FreeType( &library ); if ( error ) { ... }  error = FT_New_Memory_Face( library,                             buffer, /* 缓存的第一个字节 */                             size, /* 缓存的大小(以字节表示) */                             0, /* face索引 (face_index) */                             &face ); if ( error ) { ... }
As you can see, FT_New_Memory_Face simply takes a pointer to the font file buffer and its size in bytes instead of a file pathname. Other than that, it has exactly the same semantics as FT_New_Face. 如你所看到的,FT_New_Memory_Face简单地用字体文件缓存的指针和它的大小(以字节计算)代替文件路径。除此之外,它与FT_New_Face的语义一致。 c. From other sources (compressed files, network, etc.) c. 从其他来源装载(压缩文件,网络,等) There are cases where using a file pathname or preloading the file into memory is simply not sufficient. With FreeType 2, it is possible to provide your own implementation of i/o routines. 使用文件路径或者预装载文件到内存是简单的,但还不足够。FreeType 2可以支持通过你自己实现的I/O程序来装载文件。 This is done through the FT_Open_Face function, which can be used to open a new font face with a custom input stream, select a specific driver for opening, or even pass extra parameters to the font driver when creating the object. We advise you to refer to the FreeType 2 reference manual in order to learn how to use it. 这是通过FT_Open_Face函数来完成的。FT_Open_Face可以实现使用一个自定义的输入流,选择一个特定的驱动器来打开,乃至当创建该对象时传递外部参数给字体驱动器。我们建议你查阅“FreeType 2参考手册”,学习如何使用它。 4. Accessing face content 4、访问face内容 A face object models all information that globally describes the face. Usually, this data can be accessed directly by dereferencing a handle, like in face−>num_glyphs. 一个face对象包含该face的全部全局描述信息。通常的,这些数据可以通过分别查询句柄来直接访问,例如face->num_glyphs。 The complete list of available fields in in the FT_FaceRec structure description. However, we describe here a few of them in more details: num_glyphs This variable gives the number of glyphs available in the font face. A glyph is simply a character image. It doesn't necessarily correspond to a character code though. flags A 32-bit integer containing bit flags used to describe some face properties. For example, the flag FT_FACE_FLAG_SCALABLE is used to indicate that the face's font format is scalable and that glyph images can be rendered for all character pixel sizes. For more information on face flags, please read the FreeType 2 API Reference. units_per_EM This field is only valid for scalable formats (it is set to 0 otherwise). It indicates the number of font units covered by the EM. num_fixed_sizes This field gives the number of embedded bitmap strikes in the current face. A strike is simply a series of glyph images for a given character pixel size. For example, a font face could include strikes for pixel sizes 10, 12 and 14. Note that even scalable font formats can have embedded bitmap strikes! fixed_sizes A pointer to an array of FT_Bitmap_Size elements. Each FT_Bitmap_Size indicates the horizontal and vertical character pixel sizes for each of the strikes that are present in the face.

Note that, generally speaking, these are not the cell size of the bitmap strikes.

FT_FaceRec结构描述包含了可用字段的完整列表。我们在这里详细描述其中的某些: num_glyphs 这个值给出了该字体face中可用的字形(glyphs)数目。简单来说,一个字形就是一个字符图像。但它不一定符合一个字符代码。 Flags 一个32位整数,包含一些用来描述face特性的位标记。例如,标记FT_FACE_FLAG_SCALABLE用来指示该face的字体格式是可伸缩并且该字形图像可以渲染到任何字符象素尺寸。要了解face标记的更多信息,请阅读“FreeType 2 API 参考”。 Units_per_EM 这个字段只对可伸缩格式有效,在其他格式它将会置为0。它指示了EM所覆盖的字体单位的个数。 Num_fixed_size 这个字段给出了当前face中嵌入的位图的个数。简单来说,一个strike就是某一特定字符象素尺寸下的一系列字形图像。例如,一个字体face可以包含象素尺寸为10、12和14的strike。要注意的是即使是可伸缩的字体格式野可以包含嵌入的位图! Fixed_sizes 一个指向FT_Bitmap_Size成员组成的数组的指针。每一个FT_Bitmap_Size指示face中的每一个strike的水平和垂直字符象素尺寸。

注意,通常来说,这不是位图strike的单元尺寸。

5. Setting the current pixel size 5、设置当前象素尺寸 FreeType 2 uses size objects to model all information related to a given character size for a given face. For example, a size object will hold the value of certain metrics like the ascender or text height, expressed in 1/64th of a pixel, for a character size of 12 points. 对于特定face中与字符大小相关的信息,FreeType 2使用size对象来构造。例如,当字符大小为12点时,使用一个size对象以1/64象素为单位保存某些规格(如ascender或者文字高度)的值。 When the FT_New_Face function is called (or one of its cousins), it automatically creates a new size object for the returned face. This size object is directly accessible as face−>size. 当FT_New_Face或它的亲戚被调用,它会自动在face中新建一个size对象,并返回。该size对象可以通过face->size直接访问。 NOTE: A single face object can deal with one or more size objects at a time; however, this is something that few programmers really need to do. We have thus decided to simplify the API for the most common use (i.e., one size per face) while keeping this feature available through additional functions. 注意:一个face对象可以同时处理一个或多个size对象,但只有很少程序员需要用到这个功能,因而,我们决定简化该API(例如,每个face对象只拥有一个size对象),但是这个特性我们仍然通过附加的函数提供。 When a new face object is created, all elements are set to 0 during initialization. To populate the structure with sensible values, simply call FT_Set_Char_Size. Here is an example where the character size is set to 16pt for a 300×300dpi device:
 error = FT_Set_Char_Size( face,   /* handle to face object */                           0,      /* char_width in 1/64th of points */                           16*64,  /* char_height in 1/64th of points */                           300,    /* horizontal device resolution */                           300 );  /* vertical device resolution */
当一个新的face对象建立时,所有成员都在初始化阶段0设为0。调用FT_Set_Char_Size对这个结构进行赋值。这里有一个例子,它在一个300x300dpi设备上把字符大小设置为16pt。
 error = FT_Set_Char_Size( face,   /* face对象的句柄 */                           0,      /* 以1/64点为单位的字符宽度 */                           16*64,  /* 以1/64点为单位的字符高度 */                           300,    /* 设备水平分辨率 */                           300 );  /* 设备垂直分辨率 */
Some notes:
  • The character widths and heights are specified in 1/64th of points. A point is a physical distance, equaling 1/72th of an inch. Normally, it is not equivalent to a pixel.
  • The horizontal and vertical device resolutions are expressed in dots-per-inch, or dpi. Normal values are 72 or 96 dpi for display devices like the screen. The resolution is used to compute the character pixel size from the character point size.
  • A value of 0 for the character width means ‘same as character height’, a value of 0 for the character height means ‘same as character width’. Otherwise, it is possible to specify different character widths and heights.
  • Using a value of 0 for the horizontal or vertical resolution means 72 dpi, which is the default.
  • The first argument is a handle to a face object, not a size object.
注意:
  • 字符宽度和高度以1/64点为单位表示。一个点是一个1/72英寸的物理距离。通常,这不等于一个象素。
  • 设备的水平和垂直分辨率以每英寸点数(dpi)为单位表示。显示设备(如显示器)的常规值为72dpi或96dpi。这个分辨率是用来从字符点数计算字符象素大小的。
  • 字符宽度为0意味着“与字符高度相同”,字符高度为0意味着“与字符宽度相同”。对于其他情况则意味着指定不一样的字符宽度和高度。
  • 水平或垂直分辨率为0时表示使用默认值72dpi。
  • 第一个参数是face对象的句柄,不是size对象的。
This function computes the character pixel size that corresponds to the character width and height and device resolutions. However, if you want to specify the pixel sizes yourself, you can simply call FT_Set_Pixel_Sizes, as in
 error = FT_Set_Pixel_Sizes( face,  /* handle to face object */                             0,     /* pixel_width */                             16 );  /* pixel_height */
这个函数计算对应字符宽度、高度和设备分辨率的字符象素大小。然而,如果你想自己指定象素大小,你可以简单地调用FT_Set_Pixel_Sizes,就像这样:
 error = FT_Set_Pixel_Sizes( face,  /* face对象句柄 */                             0,     /* 象素宽度 */                             16 );  /* 象素高度 */
This example will set the character pixel sizes to 16×16 pixels. As previously, a value of 0 for one of the dimensions means ‘same as the other’. 这个例子把字符象素设置为16x16象素。如前所说的,尺寸中的任一个为0意味着“与另一个尺寸值相等”。 Note that both functions return an error code. Usually, an error occurs with a fixed-size font format (like FNT or PCF) when trying to set the pixel size to a value that is not listed in the face->fixed_sizes array. 注意这两个函数都返回错误码。通常,错误会发生在尝试对定长字体格式(如FNT或PCF)设置不在 face->fixed_size 数组中的象素尺寸值。 6. Loading a glyph image 6、装载一个字形图像 a. Converting a character code into a glyph index a. 把一个字符码转换为一个字形索引 Usually, an application wants to load a glyph image based on its character code, which is a unique value that defines the character for a given encoding. For example, the character code 65 represents the 'A' in ASCII encoding. 通常,一个应用程序想通过字符码来装载它的字形图像。字符码是一个特定编码中代表该字符的数值。例如,字符码64代表了ASCII编码中的'A'。 A face object contains one or more tables, called charmaps, that are used to convert character codes to glyph indices. For example, most TrueType fonts contain two charmaps. One is used to convert Unicode character codes to glyph indices, the other is used to convert Apple Roman encoding into glyph indices. Such fonts can then be used either on Windows (which uses Unicode) and Macintosh (which uses Apple Roman). Note also that a given charmap might not map to all the glyphs present in the font. 一个face对象包含一个或多个字符表(charmap),字符表是用来转换字符码到字形索引的。例如,很多TrueType字体包含两个字符表,一个用来转换Unicode字符码到字形索引,另一个用来转换Apple Roman编码到字形索引。这样的字体既可以用在Windows(使用Unicode)和Macintosh(使用Apple Roman)。同时要注意,一个特定的字符表可能没有覆盖完字体里面的全部字形。 By default, when a new face object is created, it selects a Unicode charmap. FreeType tries to emulate a Unicode charmap if the font doesn't contain such a charmap, based on glyph names. Note that it is possible that the emulation misses glyphs if glyph names are non-standard. For some fonts, including symbol fonts and (older) fonts for Asian scripts, no Unicode emulation is possible at all. 当新建一个face对象时,它默认选择Unicode字符表。如果字体没包含Unicode字符表,FreeType会尝试在字形名的基础上模拟一个。注意,如果字形名是不标准的那么模拟的字符表有可能遗漏某些字形。对于某些字体,包括符号字体和旧的亚洲手写字体,Unicode模拟是不可能的。 We will describe later how to look for specific charmaps in a face. For now, we will assume that the face contains at least a Unicode charmap that was selected during a call to FT_New_Face. To convert a Unicode character code to a font glyph index, we use FT_Get_Char_Index, as in
 glyph_index = FT_Get_Char_Index( face, charcode );
我们将在稍后叙述如何寻找face中特定的字符表。现在我们假设face包含至少一个Unicode字符表,并且在调用FT_New_Face时已经被选中。我们使用FT_Get_Char_Index把一个Unicode字符码转换为字形索引,如下所示:
 glyph_index = FT_Get_Char_Index( face, charcode );
This will look the glyph index corresponding to the given charcode in the charmap that is currently selected for the face. If no charmap was selected, the function simply returns the charcode. 这个函数会在face里被选中的字符表中查找与给出的字符码对应的字形索引。如果没有字符表被选中,这个函数简单的返回字符码。 Note that this is one of the rare FreeType functions that do not return an error code. However, when a given character code has no glyph image in the face, the value 0 is returned. By convention, it always correspond to a special glyph image called the missing glyph, which is commonly displayed as a box or a space. 注意,这个函数是FreeType中罕有的不返回错误码的函数中的一个。然而,当一个特定的字符码在face中没有字形图像,函数返回0。按照约定,它对应一个特殊的字形图像――缺失字形,通常会显示一个框或一个空格。 b. Loading a glyph from the face b. 从face中装载一个字形 Once you have a glyph index, you can load the corresponding glyph image. The latter can be stored in various formats within the font file. For fixed-size formats like FNT or PCF, each image is a bitmap. Scalable formats like TrueType or Type 1 use vectorial shapes, named outlines to describe each glyph. Some formats may have even more exotic ways of representing glyphs (e.g., MetaFont — but this format is not supported). Fortunately, FreeType 2 is flexible enough to support any kind of glyph format through a simple API. 一旦你获得了字形索引,你便可以装载对应的字形图像。在不同的字体中字形图像存储为不同的格式。对于固定尺寸字体格式,如FNT或者PCF,每一个图像都是一个位图。对于可伸缩字体格式,如TrueType或者Type1,使用名为轮廓(outlines)的矢量形状来描述每一个字形。一些字体格式可能有更特殊的途径来表示字形(如MetaFont――但这个格式不被支持)。幸运的,FreeType2有足够的灵活性,可以通过一个简单的API支持任何类型的字形格式。 The glyph image is always stored in a special object called a glyph slot. As its name suggests, a glyph slot is simply a container that is able to hold one glyph image at a time, be it a bitmap, an outline, or something else. Each face object has a single glyph slot object that can be accessed as face->glyph. Its fields are explained by the FT_GlyphSlotRec structure documentation. 字形图像存储在一个特别的对象――字形槽(glyph slot)中。就如其名所暗示的,一个字形槽只是一个简单的容器,它一次只能容纳一个字形图像,可以是位图,可以是轮廓,或者其他。每一个face对象都有一个字形槽对象,可以通过face->glyph来访问。它的字段在FT_GlyphSlotRec结构的文档中解释了。 Loading a glyph image into the slot is performed by calling FT_Load_Glyph as in
 error = FT_Load_Glyph( face,          /* handle to face object */                        glyph_index,   /* glyph index */                        load_flags );  /* load flags, see below */

The load_flags value is a set of bit flags used to indicate some special operations. The default value FT_LOAD_DEFAULT is 0.

通过调用FT_Load_Glyph来装载一个字形图像到字形槽中,如下:
 error = FT_Load_Glyph( face,          /* face对象的句柄 */                        glyph_index,   /* 字形索引 */                        load_flags );  /* 装载标志,参考下面 */

load_flags的值是位标志集合,是用来指示某些特殊操作的。其默认值是FT_LOAD_DEFAULT即0。

This function will try to load the corresponding glyph image from the face:
  • If a bitmap is found for the corresponding glyph and pixel size, it will be loaded into the slot. Embedded bitmaps are always favored over native image formats, because we assume that they are higher-quality versions of the same glyph. This can be changed by using the FT_LOAD_NO_BITMAP flag.
  • Otherwise, a native image for the glyph will be loaded. It will also be scaled to the current pixel size, as well as hinted for certain formats like TrueType and Type 1.
这个函数会设法从face中装载对应的字形图像:
  • 如果找到一个对应该字形和象素尺寸的位图,那么它将会被装载到字形槽中。嵌入的位图总是比原生的图像格式优先装载。因为我们假定对一个字形,它有更高质量的版本。这可以用FT_LOAD_NO_BITMAP标志来改变。
  • 否则,将装载一个该字形的原生图像,把它伸缩到当前的象素尺寸,并且对应如TrueType和Type1这些格式,也会完成hinted操作。
The field face−>glyph−>format describes the format used to store the glyph image in the slot. If it is not FT_GLYPH_FORMAT_BITMAP, one can immediately convert it to a bitmap through FT_Render_Glyph as in:
 error = FT_Render_Glyph( face->glyph,    /* glyph slot */                          render_mode );  /* render mode */

The parameter render_mode is a set of bit flags used to specify how to render the glyph image. Set it to FT_RENDER_MODE_NORMAL to render a high-quality anti-aliased (256 gray levels) bitmap, as this is the default. You can alternatively use FT_RENDER_MODE_MONO if you want to generate a 1-bit monochrome bitmap.

字段face->glyph->format描述了字形槽中存储的字形图像的格式。如果它的值不是FT_GLYPH_FORMAT_BITMAP,你可以通过FT_Render_Glyph把它直接转换为一个位图。如下:
 error = FT_Render_Glyph( face->glyph,    /* 字形槽 */                          render_mode );  /* 渲染模式 */

render_mode参数是一个位标志集合,用来指示如何渲染字形图像。把它设为FT_RENDER_MODE_NORMAL渲染出一个高质量的抗锯齿(256级灰度)位图。这是默认情况,如果你想生成黑白位图,可以使用FT_RENDER_MODE_MONO标志。

Once you have a bitmapped glyph image, you can access it directly through glyph->bitmap (a simple bitmap descriptor), and position it through glyph->bitmap_left and glyph->bitmap_top. 一旦你生成了一个字形图像的位图,你可以通过glyph->bitmap(一个简单的位图描述符)直接访问,同时用glyph->bitmap_left和glyph->bitmap_top来指定起始位置。 Note that bitmap_left is the horizontal distance from the current pen position to the leftmost border of the glyph bitmap, while bitmap_top is the vertical distance from the pen position (on the baseline) to the topmost border of the glyph bitmap. It is positive to indicate an upwards distance. 要注意,bitmap_left是从字形位图当前笔位置到最左边界的水平距离,而bitmap_top是从笔位置(位于基线)到最高边界得垂直距离。他么是正数,指示一个向上的距离。 The next section will give more details on the contents of a glyph slot and how to access specific glyph information (including metrics). 下一部分将给出字形槽内容的更多细节,以及如何访问特定的字形信息(包括度量)。 c. Using other charmaps c. 使用其他字符表 As said before, when a new face object is created, it will look for a Unicode charmap and select it. The currently selected charmap is accessed via face->charmap. This field is NULL when no charmap is selected, which typically happens when you create a new FT_Face object from a font file that doesn't contain a Unicode charmap (which is rather infrequent today). 如前面所说的,当一个新face对象创建时,它会寻找一个Unicode字符表并且选择它。当前被选中的字符表可以通过face->charmap 访问。当没有字符表被选中时,该字段为NULL。这种情况在你从一个不含Unicode字符表的字体文件(这种文件现在非常罕见)创建一个新的 FT_Face对象时发生。 There are two ways to select a different charmap with FreeType 2. The easiest is when the encoding you need already has a corresponding enumeration defined in FT_FREETYPE_H, for example FT_ENCODING_BIG5. In this case, you can simply call FT_Select_CharMap as in:
 error = FT_Select_CharMap( face,                /* target face object */                            FT_ENCODING_BIG5 );  /* encoding */
有两种途径可以在FreeType 2中选择不同的字符表。最轻松的途径是你所需的编码已经有对应的枚举定义在FT_FREETYPE_H中,例如FT_ENCODING_BIG5。在这种情况下,你可以简单地调用FT_Select_CharMap,如下:
 error = FT_Select_CharMap( face,                /* 目标face对象 */                            FT_ENCODING_BIG5 );  /* 编码 */
Another way is to manually parse the list of charmaps for the face; this is accessible through the fields num_charmaps and charmaps (notice the ‘s’) of the face object. As you could expect, the first is the number of charmaps in the face, while the second is a table of pointers to the charmaps embedded in the face. 另一种途径是手动为face解析字符表。这通过face对象的字段num_charmaps和charmaps(注意这是复数)来访问。如你想到的,前者是face中的字符表的数目,后者是一个嵌入在face中的指向字符表的指针表(a table of pointers to the charmaps)。 Each charmap has a few visible fields used to describe it more precisely. Mainly, one will look at charmap->platform_id and charmap->encoding_id that define a pair of values that can be used to describe the charmap in a rather generic way. 每一个字符表有一些可见的字段,用来更精确地描述它,主要用到的字段是charmap->platform_id和charmap->encoding_id。这两者定义了一个值组合,以更普通的形式用来描述该字符表。 Each value pair corresponds to a given encoding. For example, the pair (3,1) corresponds to Unicode. The list is defined in the TrueType specification but you can also use the file FT_TRUETYPE_IDS_H which defines several helpful constants to deal with them. 每一个值组合对应一个特定的编码。例如组合(3,1)对应Unicode。组合列表定义在TrueType规范中,但你也可以使用文件FT_TRUETYPE_IDS_H来处理它们,该文件定义了几个有用的常数。 To select a specific encoding, you need to find a corresponding value pair in the specification, then look for it in the charmaps list. Don't forget that there are encodings which correspond to several value pairs due to historical reasons. Here some code to do it:
 FT_CharMap found = 0; FT_CharMap charmap; int        n;  for ( n = 0; n < face->num_charmaps; n++ ) {   charmap = face->charmaps[n];   if ( charmap->platform_id == my_platform_id &&        charmap->encoding_id == my_encoding_id )   {     found = charmap;     break;   } }  if ( !found ) { ... }  /* now, select the charmap for the face object */ error = FT_Set_CharMap( face, found ); if ( error ) { ... }
要选择一个具体的编码,你需要在规范中找到一个对应的值组合,然后在字符表列表中寻找它。别忘记,由于历史的原因,某些编码会对应几个值组合。这里是一些代码:
 FT_CharMap found = 0; FT_CharMap charmap; int        n;  for ( n = 0; n < face->num_charmaps; n++ ) {   charmap = face->charmaps[n];   if ( charmap->platform_id == my_platform_id &&        charmap->encoding_id == my_encoding_id )   {     found = charmap;     break;   } }  if ( !found ) { ... }  /* 现在,选择face对象的字符表 */ error = FT_Set_CharMap( face, found ); if ( error ) { ... }
Once a charmap has been selected, either through FT_Select_CharMap or FT_Set_CharMap, it is used by all subsequent calls to FT_Get_Char_Index. 一旦某个字符表被选中,无论通过FT_Select_CharMap还是通过FT_Set_CharMap,它都会在后面的FT_Get_Char_Index调用使用。 d. Glyph transformations d. 字形变换 It is possible to specify an affine transformation to be applied to glyph images when they are loaded. Of course, this will only work for scalable (vectorial) font formats. 当字形图像被装载时,可以对该字形图像进行仿射变换。当然,这只适用于可伸缩(矢量)字体格式。 To do that, simply call FT_Set_Transform, as in:
 error = FT_Set_Transform( face,      /* target face object */                           &matrix,   /* pointer to 2x2 matrix */                           &delta );  /* pointer to 2d vector */
简单地调用FT_Set_Transform来完成这个工作,如下:
 error = FT_Set_Transform( face,      /* 目标face对象 */                           &matrix,   /* 指向2x2矩阵的指针 */                           &delta );  /* 指向2维矢量的指针 */
This function will set the current transform for a given face object. Its second parameter is a pointer to a simple FT_Matrix structure that describes a 2×2 affine matrix. The third parameter is a pointer to a FT_Vector structure that describes a simple two-dimensional vector that is used to translate the glyph image after the 2×2 transformation. 这个函数将对指定的face对象设置变换。它的第二个参数是一个指向FT_Matrix结构的指针。该结构描述了一个2x2仿射矩阵。第三个参数是一个指向FT_Vector结构的指针。该结构描述了一个简单的二维矢量。该矢量用来在2x2变换后对字形图像平移。 Note that the matrix pointer can be set to NULL, in which case the identity transform will be used. Coefficients of the matrix are otherwise in 16.16 fixed float units. 注意,矩阵指针可以设置为NULL,在这种情况下将进行恒等变换。矩阵的系数是16.16形式的固定浮点单位。 The vector pointer can also be set to NULL (in which case a delta of (0,0) will be used). The vector coordinates are expressed in 1/64th of a pixel (also known as 26.6 fixed floats). 矢量指针也可以设置为NULL,在这种情况下将使用(0, 0)的delta。矢量坐标以一个象素的1/64为单位表示(即通常所说的26.6固定浮点格式)。 NOTE: The transformation is applied to every glyph that is loaded through FT_Load_Glyph and is completely independent of any hinting process. This means that you won't get the same results if you load a glyph at the size of 24 pixels, or a glyph at the size at 12 pixels scaled by 2 through a transform, because the hints will have been computed differently (except you have disabled hints). 注意:变换将适用于使用FT_Load_Glyph装载的全部字形,并且完全独立于任何hinting处理。这意味着你对一个12象素的字形进行2倍放大变换不会得到与24象素字形相同的结果(除非你禁止hints)。 If you ever need to use a non-orthogonal transformation with optimal hints, you first have to decompose your transformation into a scaling part and a rotation/shearing part. Use the scaling part to compute a new character pixel size, then the other one to call FT_Set_Transform. This is explained in details in a later section of this tutorial. 如果你需要使用非正交变换和最佳hints,你首先必须把你的变换分解为一个伸缩部分和一个旋转/剪切部分。使用伸缩部分来计算一个新的字符象素大小,然后使用旋转/剪切部分来调用FT_Set_Transform。这在本教程的后面部分有详细解释。 Loading a glyph bitmap with a non-identity transformation works; the transformation is ignored in this case. 同时要注意,对一个字形位图进行非同一性变换将产生错误。 7. Simple text rendering 7、简单的文字渲染 We will now present a very simple example used to render a string of 8-bit Latin-1 text, assuming a face that contains a Unicode charmap 现在我们将给出一个非常简单的例子程序,该例子程序渲染一个8位Latin-1文本字符串,并且假定face包含一个Unicode字符表。

The idea is to create a loop that will, on each iteration, load one glyph image, convert it to an anti-aliased bitmap, draw it on the target surface, then increment the current pen position.

该程序的思想是建立一个循环,在该循环的每一次迭代中装载一个字形图像,把它转换为一个抗锯齿位图,把它绘制到目标表面(surface)上,然后增加当前笔的位置。 a. Basic code a. 基本代码 The following code performs our simple text rendering with the functions previously described.
 FT_GlyphSlot slot = face->glyph;  /* a small shortcut */ int          pen_x, pen_y, n;  ... initialize library ... ... create face object ... ... set character size ...  pen_x = 300; pen_y = 200;  for ( n = 0; n < num_chars; n++ ) {   FT_UInt glyph_index;    /* retrieve glyph index from character code */   glyph_index = FT_Get_Char_Index( face, text[n] );    /* load glyph image into the slot (erase previous one) */   error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );   if ( error )     continue; /* ignore errors */    /* convert to an anti-aliased bitmap */   error = FT_Render_Glyph( face->glyph, FT_RENDER_MODE_NORMAL );   if ( error )     continue;    /* now, draw to our target surface */   my_draw_bitmap( &slot->bitmap,                   pen_x + slot->bitmap_left,                   pen_y - slot->bitmap_top );    /* increment pen position */   pen_x += slot->advance.x >> 6;   pen_y += slot->advance.y >> 6; /* not useful for now */ }
下面的代码完成我们上面提到的简单文本渲染和其他功能。
 FT_GlyphSlot slot = face->glyph;  /* 一个小捷径 */ int          pen_x, pen_y, n;  ... 初始化库 ... ... 创建face对象 ... ... 设置字符尺寸 ...  pen_x = 300; pen_y = 200;  for ( n = 0; n < num_chars; n++ ) {   FT_UInt glyph_index;    /* 从字符码检索字形索引 */   glyph_index = FT_Get_Char_Index( face, text[n] );    /* 装载字形图像到字形槽(将会抹掉先前的字形图像) */   error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );   if ( error )     continue; /* 忽略错误 */    /* 转换为一个抗锯齿位图 */   error = FT_Render_Glyph( face->glyph, FT_RENDER_MODE_NORMAL );   if ( error )     continue;    /* 现在,绘制到我们的目标表面(surface) */   my_draw_bitmap( &slot->bitmap,                   pen_x + slot->bitmap_left,                   pen_y - slot->bitmap_top );    /* 增加笔位置 */   pen_x += slot->advance.x >> 6;   pen_y += slot->advance.y >> 6; /* 现在是没用的 */ }
This code needs a few explanations:
  • We define a handle named slot that points to the face object's glyph slot. (The type FT_GlyphSlot is a pointer). That is a convenience to avoid using face->glyph->XXX every time.
  • We increment the pen position with the vector slot->advance, which correspond to the glyph's advance width (also known as its escapement). The advance vector is expressed in 1/64th of pixels, and is truncated to integer pixels on each iteration.
  • The function my_draw_bitmap is not part of FreeType but must be provided by the application to draw the bitmap to the target surface. In this example, it takes a pointer to a FT_Bitmap descriptor and the position of its top-left corner as arguments.
  • The value of slot->bitmap_top is positive for an upwards vertical distance. Assuming that the coordinates taken by my_draw_bitmap use the opposite convention (increasing Y corresponds to downwards scanlines), we substract it from pen_y, instead of adding to it.
这个代码需要一些解释:
  • 我们定义了一个名为slot的句柄,它指向face对象的字形槽。(FT_GlyphSlot类型是一个指针)。这是为了便于避免每次都使用face->glyph->XXX。
  • 我们以slot->advance增加笔位置,slot->advance符合字形的步进宽度(也就是通常所说的走格(escapement))。步进矢量以象素的1/64为单位表示,并且在每一次迭代中删减为整数象素。
  • 函数my_draw_bitmap不是FreeType的一部分,但必须由应用程序提供以用来绘制位图到目标表面。在这个例子中,该函数以一个FT_Bitmap描述符的指针和它的左上角位置为参数。
  • Slot->bitmap_top的值是正数,指字形图像顶点与pen_y的垂直距离。我们假定my_draw_bitmap采用的坐标使用一样的约定(增加Y值对应向下的扫描线)。我们用pen_y减它,而不是加它。
b. Refined code b. 精练的代码 The following code is a refined version of the example above. It uses features and functions of FreeType 2 that have not yet been introduced, and which are explained below:
 FT_GlyphSlot slot = face->glyph; /* a small shortcut */ FT_UInt      glyph_index; int          pen_x, pen_y, n;  ... initialize library ... ... create face object ... ... set character size ...  pen_x = 300; pen_y = 200;  for ( n = 0; n < num_chars; n++ ) {   /* 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 */   my_draw_bitmap( &slot->bitmap,                   pen_x + slot->bitmap_left,                   pen_y - slot->bitmap_top );    /* increment pen position */   pen_x += slot->advance.x >> 6; }
下面的代码是上面例子程序的精练版本。它使用了FreeType 2中我们还没有介绍的特性和函数,我们将在下面解释:
 FT_GlyphSlot slot = face->glyph; /* 一个小捷径 */ FT_UInt      glyph_index; int          pen_x, pen_y, n;  ... 初始化库 ... ... 创建face对象 ... ... 设置字符尺寸 ...  pen_x = 300; pen_y = 200;  for ( n = 0; n < num_chars; n++ ) {   /* 装载字形图像到字形槽(将会抹掉先前的字形图像) */   error = FT_Load_Char( face, text[n], FT_LOAD_RENDER );   if ( error )     continue; /* 忽略错误 */    /* 现在,绘制到我们的目标表面(surface) */   my_draw_bitmap( &slot->bitmap,                   pen_x + slot->bitmap_left,                   pen_y - slot->bitmap_top );    /* 增加笔位置 */   pen_x += slot->advance.x >> 6; }
We have reduced the size of our code, but it does exactly the same thing:
  • We use the function FT_Load_Char instead of FT_Load_Glyph. As you probably imagine, it is equivalent to calling FT_Get_Char_Index then FT_Get_Load_Glyph.
  • We do not use FT_LOAD_DEFAULT for the loading mode, but the bit flag FT_LOAD_RENDER. It indicates that the glyph image must be immediately converted to an anti-aliased bitmap. This is of course a shortcut that avoids calling FT_Render_Glyph explicitly but is strictly equivalent.
Note that you can also specify that you want a monochrome bitmap instead by using the addition FT_LOAD_MONOCHROME load flag.
我们简化了代码的长度,但它完成相同的工作:
  • 我们使用函数FT_Loac_Char代替FT_Load_Glyph。如你大概想到的,它相当于先调用GT_Get_Char_Index然后调用FT_Get_Load_Glyph。
  • 我们不使用FT_LOAD_DEFAULT作为装载模式,使用FT_LOAD_RENDER。它指示了字形图像必须立即转换为一个抗锯齿位图。这是一个捷径,可以取消明显的调用FT_Render_Glyph,但功能是相同的。
注意,你也可以指定通过附加FT_LOAD_MONOCHROME装载标志来获得一个单色位图。
c. More advanced rendering c. 更高级的渲染 Let us try to render transformed text now (for example through a rotation). We can do this using FT_Set_Transform. Here is how to do it:
 FT_GlyphSlot slot; FT_Matrix    matrix;       /* transformation matrix */ FT_UInt      glyph_index; FT_Vector    pen;          /* untransformed origin */ int          n;  ... initialize library ... ... create face object ... ... set character size ...  slot = face->glyph; /* a small shortcut */  /* set up matrix */ 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 );  /* the pen position in 26.6 cartesian space coordinates */ /* start at (300,200) */ pen.x = 300 * 64; pen.y = ( my_target_height - 200 ) * 64;  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) */   my_draw_bitmap( &slot->bitmap,                   slot->bitmap_left,                   my_target_height - slot->bitmap_top );    /* increment pen position */   pen.x += slot->advance.x;   pen.y += slot->advance.y; }
现在,让我们来尝试渲染变换文字(例如通过一个环)。我们可以用FT_Set_Transform来完成。这里是示例代码:
 FT_GlyphSlot slot; FT_Matrix    matrix;       /* 变换矩阵 */ FT_UInt      glyph_index; FT_Vector    pen;          /* 非变换原点 */ int          n;  ... 初始化库 ... ... 创建face对象 ... ... 设置字符尺寸 ...  slot = face->glyph; /* 一个小捷径 */  /* 准备矩阵 */ 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 );  /* 26.6 笛卡儿空间坐标中笔的位置,以(300, 200)为起始 */ pen.x = 300 * 64; pen.y = ( my_target_height - 200 ) * 64;  for ( n = 0; n < num_chars; n++ ) {   /* 设置变换 */   FT_Set_Transform( face, &matrix, &pen );    /* 装载字形图像到字形槽(将会抹掉先前的字形图像) */   error = FT_Load_Char( face, text[n], FT_LOAD_RENDER );   if ( error )     continue; /* 忽略错误 */
   /* 现在,绘制到我们的目标表面(变换位置) */   my_draw_bitmap( &slot->bitmap,                   slot->bitmap_left,                   my_target_height - slot->bitmap_top );    /* 增加笔位置 */   pen.x += slot->advance.x;   pen.y += slot->advance.y; }
Some remarks:
  • We now use a vector of type FT_Vector to store the pen position, with coordinates expressed as 1/64th of pixels, hence a multiplication. The position is expressed in cartesian space.
  • Glyph images are always loaded, transformed, and described in the cartesian coordinate system in FreeType (which means that increasing Y corresponds to upper scanlines), unlike the system typically used for bitmaps (where the topmost scanline has coordinate 0). We must thus convert between the two systems when we define the pen position, and when we compute the topleft position of the bitmap.
  • We set the transformation on each glyph to indicate the rotation matrix as well as a delta that will move the transformed image to the current pen position (in cartesian space, not bitmap space).
As a consequence, the values of bitmap_left and bitmap_top correspond to the bitmap origin in target space pixels. We thus don't add pen.x or pen.y to their values when calling my_draw_bitmap.
  • The advance width is always returned transformed, which is why it can be directly added to the current pen position. Note that it is not rounded this time.
一些说明:
  • 现在我们使用一个FT_Vector类型的矢量来存储笔位置,其坐标以象素的1/64为单位表示,并且倍增。该位置表示在笛卡儿空间。
  • 不同于系统典型的对位图使用的坐标系(其最高的扫描线是坐标0),FreeType中,字形图像的装载、变换和描述总是采用笛卡儿坐标系(这意味着增加Y对应向上的扫描线)。因此当我们定义笔位置和计算位图左上角时必须在两个系统之间转换。
  • 我们对每一个字形设置变换来指示旋转矩阵以及使用一个delta来移动转换后的图像到当前笔位置(在笛卡儿空间,不是位图空间)。
结果, bitmap_left和bitmap_top的值对应目标空间象素中的位图原点。因此,我们在调用my_draw_bitmap时不在它们的值上加 pen.x或pen.y。
  • 步进宽度总会在变换后返回,这就是它可以直接加到当前笔位置的原因。注意,这次它不会四舍五入。
A complete source code example can be found here. 一个例子完整的源代码可以在这里找到。 It is important to note that, while this example is a bit more complex than the previous one, it is strictly equivalent for the case where the transform is the identity. Hence it can be used as a replacement (but a more powerful one). 要很注意,虽然这个例子比前面的更复杂,但是变换效果是完全一致的。因此它可以作为一个替换(但更强大)。 It has however a few shortcomings that we will explain, and solve, in the next part of this tutorial. 然而该例子有少许缺点,我们将在本教程的下一部分中解释和解决。 Conclusion 结论 In this first section, you have learned the basics of FreeType 2, as well as sufficient knowledge how to render rotated text. 在这个部分,你已经学习了FreeType2的基础以及渲染旋转文字的充分知识。 The next section will dive into more details of the API in order to let you access glyph metrics and images directly, as well as how to deal with scaling, hinting, kerning, etc. 下一部分将深入了解FreeType 2 API更详细的资料,它可以让你直接访问字形度量标准和字形图像,还能让你学习到如何处理缩放、hinting、字距调整,等等。 The third section will discuss issues like modules, caching and a few other advanced topics like how to use multiple size objects with a single face. [This part hasn't been written yet.] 第三部分将讨论模块、缓存和其他高级主题,如如何在一个face中使用多个尺寸对象。【这部分还没有编写】 Last update: 11-May-2006 最后更新:2006年5月11日  
原创粉丝点击