1 <!doctype html public "-//w3c//dtd html 4.0 transitional//en">
4 <meta http-equiv="Content-Type"
5 content="text/html; charset=iso-8859-1">
7 content="David Turner">
8 <title>FreeType 2 Tutorial</title>
18 FreeType 2.0 Tutorial<br>
19 Step 2 - managing glyphs
23 © 2000 David Turner
24 (<a href="mailto:david@freetype.org">david@freetype.org</a>)<br>
25 © 2000 The FreeType Development Team
26 (<a href="http://www.freetype.org">www.freetype.org</a>)
39 <p>This is the second section of the FreeType 2 tutorial. It will teach
40 you the following:</p>
43 <li>how to retrieve glyph metrics</li>
44 <li>how to easily manage glyph images</li>
45 <li>how to retrieve global metrics (including kerning)</li>
46 <li>how to render a simple string of text, with kerning</li>
47 <li>how to render a centered string of text (with kerning)</li>
48 <li>how to render a transformed string of text (with centering)</li>
49 <li>finally, how to access metrics in design font units when needed,
50 and how to scale them to device space.</li>
59 <p>Glyph metrics are, as their name suggests, certain distances associated
60 to each glyph in order to describe how to use it to layout text.</p>
62 <p>There are usually two sets of metrics for a single glyph: those used to
63 layout the glyph in horizontal text layouts (like latin, cyrillic,
64 arabic, hebrew, etc..), and those used to layout the glyph in vertical
65 text layouts (like some layouts of Chinese, Japanese, Korean, and
68 <p>Note that only a few font formats provide vertical metrics. You can
69 test wether a given face object contains them by using the macro
70 <tt><b>FT_HAS_VERTICAL(face)</b></tt>, which is true when appropriate.</p>
72 <p>Individual glyph metrics can be accessed by first loading the glyph
73 in a face's glyph slot, then accessing them through the
74 <tt><b>face->glyph->metrics</b></tt> structure. This will be detailed
75 later, for now, we'll see that it contains the following fields:</p>
77 <center><table width="90%" cellpadding=5><tr valign=top><td>
80 <p>This is the width of the glyph image's bounding box. It is independent
81 of layout direction.</p>
82 </td></tr><tr valign=top><td>
83 <tt><b>height</b></tt>
85 <p>This is the height of the glyph image's bounding box. It is independent
86 of layout direction.</p>
87 </td></tr><tr valign=top><td>
88 <tt><b>horiBearingX</b></tt>
90 <p>For <em>horizontal text layouts</em>, this is the horizontal distance from
91 the current cursor position to the left-most border of the glyph image's
93 </td></tr><tr valign=top><td>
94 <tt><b>horiBearingY</b></tt>
96 <p>For <em>horizontal text layouts</em>, this is the vertical distance from
97 the current cursor position (on the baseline) to the top-most border of
98 the glyph image's bounding box.</p>
99 </td></tr><tr valign=top><td>
100 <tt><b>horiAdvance</b></tt>
102 <p>For <em>horizontal text layouts</em>, this is the horizontal distance
103 used to increment the pen position when the glyph is drawn as part of
104 a string of text.</p>
105 </td></tr><tr valign=top><td>
106 <tt><b>vertBearingX</b></tt>
108 <p>For <em>vertical text layouts</em>, this is the horizontal distance from
109 the current cursor position to the left-most border of the glyph image's
111 </td></tr><tr valign=top><td>
112 <tt><b>vertBearingY</b></tt>
114 <p>For <em>vertical text layouts</em>, this is the vertical distance from
115 the current cursor position (on the baseline) to the top-most border of
116 the glyph image's bounding box.</p>
117 </td></tr><tr valign=top><td>
118 <tt><b>vertAdvance</b></tt>
120 <p>For <em>vertical text layouts</em>, this is the vertical distance
121 used to increment the pen position when the glyph is drawn as part of
122 a string of text.</p>
123 </td></tr></table></center>
125 <p><font color="red">NOTA BENE: As all fonts do not contain vertical
126 metrics, the values of <tt>vertBearingX</tt>, <tt>vertBearingY</tt>
127 and <tt>vertAdvance</tt> should not be considered reliable when
128 <tt><b>FT_HAS_VERTICAL(face)</b></tt> is false.</font></p>
130 <p>The following graphics illustrate the metrics more clearly. First, for
131 horizontal metrics, where the baseline is the horizontal axis :</p>
133 <center><img src="metrics.png" width=388 height=253></center>
135 <p>For vertical text layouts, the baseline is vertical and is the
138 <center><img src="metrics2.png" width=294 height=278></center>
141 <p>The metrics found in <tt>face->glyph->metrics</tt> are normally
142 expressed in 26.6 pixels (i.e 1/64th of pixels), unless you use
143 the <tt><b>FT_LOAD_NO_SCALE</b></tt> flag when calling
144 <tt>FT_Load_Glyph</tt> or <tt>FT_Load_Char</tt>. In this case,
145 the metrics will be expressed in original font units.</p>
147 <p>The glyph slot object has also a few other interesting fields
148 that will ease a developer's work. You can access them though
149 <tt><b>face->glyph->???</b></tt> :</p>
151 <center><table width="90%" cellpadding=5><tr valign=top><td>
152 <b><tt>advance</tt></b>
154 <p>This field is a <tt>FT_Vector</tt> which holds the transformed
155 advance for the glyph. That's useful when you're using a transform
156 through <tt>FT_Set_Transform</tt>, as shown in the rotated text
157 example of section I. Other than that, its value is
158 by default (metrics.horiAdvance,0), unless you specify
159 <tt><b>FT_LOAD_VERTICAL</b></tt> when loading the glyph image;
160 it will then be (0,metrics.vertAdvance)</p>
161 </td></tr><tr valign=top><td>
162 <b><tt>linearHoriAdvance</tt></b>
165 This field contains the linearly-scaled value of the glyph's horizontal
166 advance width. Indeed, the value of <tt>metrics.horiAdvance</tt> that is
167 returned in the glyph slot is normally rounded to integer pixel
168 coordinates (i.e., it will be a multiple of 64) by the font driver used
169 to load the glyph image. <tt>linearHoriAdvance</tt> is a 16.16 fixed float
170 number that gives the value of the original glyph advance width in
171 1/65536th of pixels. It can be use to perform pseudo device-independent
173 </td></tr><tr valign=top><td>
174 <b><tt>linearVertAdvance</tt></b>
176 <p>This is the same thing as <tt><b>linearHoriAdvance</b></tt> for the
177 glyph's vertical advance height. Its value is only reliable if the font
178 face contains vertical metrics.</p>
179 </td></tr></table></center>
186 2. Managing glyph images:
189 <p>The glyph image that is loaded in a glyph slot can be converted into
190 a bitmap, either by using <tt>FT_LOAD_RENDER</tt> when loading it, or
191 by calling <tt>FT_Render_Glyph</tt>. Each time you load a new glyph
192 image, the previous one is erased from the glyph slot.</p>
194 <p>There are times however where you may need to extract this image from
195 the glyph slot, in order to cache it within your application, and
196 even perform additional transforms and measures on it before converting
200 <p>The FreeType 2 API has a specific extension which is capable of dealing
201 with glyph images in a flexible and generic way. To use it, you first need
202 to include the "<tt>ftglyph.h</tt>" header file, as in:</p>
204 <pre><font color="blue">
205 #include <freetype/ftglyph.h>
208 <p>We will now explain how to use the functions defined in this file:</p>
210 <h4>a. Extracting the glyph image:</h4>
212 <p>You can extract a single glyph image very easily. Here's some code
213 that shows how to do it:</p>
215 <pre><font color="blue">
216 FT_Glyph glyph; <font color="gray">// handle to glyph image</font>
219 error = FT_Load_Glyph( face, glyph, FT_LOAD_NORMAL );
222 error = FT_Get_Glyph( face->glyph, &glyph );
226 <p>As you see, we have:</p>
230 Created a variable, named <tt>glyph</tt>, of type <tt>FT_Glyph</tt>.
231 This is a handle (pointer) to an individual glyph image.
235 Loaded the glyph image normally in the face's glyph slot. We did not
236 use <tt>FT_LOAD_RENDER</tt> because we want to grab a scalable glyph
237 image, in order to later transform it.
241 Copy the glyph image from the slot into a new <tt>FT_Glyph</tt> object,
242 by calling <tt><b>FT_Get_Glyph</b></tt>. This function returns an error
243 code and sets <tt>glyph</tt>.
247 <p>It is important to note that the extracted glyph is in the same format
248 than the original one that is still in the slot. For example, if we're
249 loading a glyph from a TrueType font file, the glyph image will really
250 be a scalable vector outline.</p>
252 <p>You can access the field <tt><b>glyph->format</b></tt> if you want to
253 know exactly how the glyph is modeled and stored. A new glyph object can
254 be destroyed with a call to <tt><b>FT_Done_Glyph</b></tt>.</p>
256 <p>The glyph object contains exactly one glyph image and a 2D vector
257 representing the glyph's advance in 16.16 fixed float coordinates.
258 The latter can be accessed directly as <tt><b>glyph->advance</b></tt>
261 <p><font color="red">Note that unlike
262 other FreeType objects, the library doesn't keeps a list of all
263 allocated glyph objects. This means you'll need to destroy them
264 yourself, instead of relying on <tt>FT_Done_FreeType</tt> doing
265 all the clean-up.</font></p>
267 <h4>b. Transforming & copying the glyph image</h4>
269 <p>If the glyph image is scalable (i.e. if <tt>glyph->format</tt> is not
270 equal to <tt>ft_glyph_format_bitmap</tt>), it is possible to transform
271 the image anytime by a call to <tt><b>FT_Glyph_Transform</b></tt>.</p>
273 <p>You can also copy a single glyph image with <tt><b>FT_Glyph_Copy</b></tt>.
274 Here's some example code:</p>
276 <pre><font color="blue">
277 FT_Glyph glyph, glyph2;
282 .. load glyph image in "glyph" ..
284 <font color="gray">// copy glyph to glyph2
286 error = FT_Glyph_Copy( glyph, &glyph2 );
287 if (error) { ... could not copy (out of memory) }
289 <font color="gray">// translate "glyph"
291 delta.x = -100 * 64; // coordinates are in 26.6 pixels
294 FT_Glyph_Transform( glyph, 0, &delta );
296 <font color="gray">// transform glyph2 (horizontal shear)
300 matrix.yx = 0.12 * 0x10000;
303 FT_Glyph_Transform( glyph2, &matrix, 0 );
306 <p>Note that the 2x2 transform matrix is always applied to the 16.16
307 advance vector in the glyph, you thus don't need to recompute it..</p>
309 <h4>c. Measuring the glyph image</h4>
311 <p>You can also retrieve the control (bounding) box of any glyph image
312 (scalable or not), through the <tt><b>FT_Glyph_Get_CBox</b></tt> function,
316 <pre><font color="blue">
319 FT_Glyph_BBox( glyph, <em>bbox_mode</em>, &bbox );
322 <p>Coordinates are relative to the glyph origin, i.e. (0,0), using the
323 Y_upwards convention. This function takes a special argument, the
324 "bbox mode", that is a set of bit flags used to indicate how
325 box coordinates are expressed. If <tt><b>ft_glyph_bbox_subpixels</b></tt>
326 is set in the bbox mode, the coordinates are returned in 26.6 pixels
327 (i.e. 1/64th of pixels). Otherwise, they're in integer pixels.</p>
329 <p>Note that the box's maximum coordinates are exclusive, which means
330 that you can always compute the width and height of the glyph image,
331 be in in integer or 26.6 pixels with:</p>
333 <pre><font color="blue">
334 width = bbox.xMax - bbox.xMin;
335 height = bbox.yMax - bbox.yMin;
338 <p>Note also that for 26.6 coordinates, if
339 <tt><b>ft_glyph_bbox_gridfit</b></tt> is set in the bbox mode,
340 the coordinates will also be grid-fitted, which corresponds to:</p>
342 <pre><font color="blue">
343 bbox.xMin = FLOOR(bbox.xMin)
344 bbox.yMin = FLOOR(bbox.yMin)
345 bbox.xMax = CEILING(bbox.xMax)
346 bbox.yMax = CEILING(bbox.yMax)
349 <p>The default value for the bbox mode, which is 0, corresponds to
350 <b><tt>ft_glyph_bbox_pixels</tt></b> (i.e. integer pixel coordinates).</p>
353 <h4>d. Converting the glyph image to a bitmap</h4>
355 <p>You may need to convert the glyph object to a bitmap once you have
356 convienently cached or transformed it. This can be done easily with
357 the <b><tt>FT_Glyph_To_Bitmap</tt></b> function. It is chared of
358 converting any glyph object into a bitmap, as in:</p>
360 <pre><font color="blue">
363 origin.x = 32; <font color="gray">/* 1/2 pixel in 26.26 format */</font>
366 error = FT_Glyph_To_Bitmap( &glyph,
367 <em>render_mode</em>,
369 1 ); <font color="gray">// destroy original image == true</font>
372 <p>We will know details this function's parameters:</p>
376 the first parameter is <em>the address of the source glyph's handle</em>.
377 When the function is called, it reads its to access the source
378 glyph object. After the call, the handle will point to a
379 <b><em>new</em></b> glyph object that contains the rendered bitmap.
383 the second parameter is a standard render mode, that is used to specify
384 what kind of bitmap we want. It can be <tt>ft_render_mode_default</tt>
385 for an 8-bit anti-aliased pixmap, or <tt>ft_render_mode_mono</tt> for
386 a 1-bit monochrome bitmap.
390 the third parameter is a pointer to a 2D vector that is used to
391 translate the source glyph image before the conversion. Note that
392 the source image will be translated back to its original position
393 (and will thus be left unchanged) after the call. If you do not need
394 to translate the source glyph before rendering, set this pointer to 0.
398 the last parameter is a boolean that indicates wether the source
399 glyph object should be destroyed by the function. By default, the
400 original glyph object is never destroyed, even if its handle is
401 lost (it's up to client applications to keep it).
405 <p>The new glyph object always contain a bitmap (when no error is returned),
406 and you must <b><em>typecast</em></b> its handle to the
407 <tt><b>FT_BitmapGlyph</b></tt> type in order to access its content.
408 This type is a sort of "subclass" of <tt>FT_Glyph</tt> that contains
409 additional fields:</p>
411 <center><table width="80%" cellpadding=5><tr valign=top><td>
414 <p>Just like the <tt><b>bitmap_left</b></tt> field of a glyph slot, this is the
415 horizontal distance from the glyph origin (0,0) to the left-most pixel
416 of the glyph bitmap. It is expressed in integer pixels.</p>
417 </td></tr><tr valign=top><td>
420 <p>Just like the <tt><b>bitmap_top</b></tt> field of a glyph slot, this is the
421 vertical distance from the glyph origin (0,0) to the top-most pixel
422 of the glyph bitmap (more exactly, to the pixel just above the bitmap).
423 This distance is expressed in integer pixels, and is positive for upwards
425 </td></tr><tr valign=top><td>
426 <tt><b>bitmap</b></tt>
428 <p>This is a bitmap descriptor for the glyph object, just like the
429 <tt><b>bitmap</b></tt> field in a glyph slot.</p>
430 </td></tr></table></center>
434 3. Global glyph metrics:
437 <p>Unlike glyph metrics, global ones are used to describe distances
438 and features of a whole font face. They can be expressed either in
439 26.6 pixels or in design "font units" for scalable formats.</p>
442 a. Design Global Metrics:
445 <p>For scalable formats, all global metrics are expressed in font units
446 in order to be later scaled to device space, according to the rules
447 described in the last chapter of this section of the tutorial. You
448 can access them directly as simple fields of a <tt>FT_Face</tt>
451 <p>However, you need to check that the font face's format is scalable
452 before using them. One can do it by using the macro
453 <tt><b>FT_IS_SCALABLE(face)</b></tt> which returns true when
456 <p>In this case, you can access the global design metrics as:</p>
458 <center><table width="90%" cellpadding=5><tr valign=top><td>
459 <tt><b>units_per_EM</b></tt>
461 <p>This is the size of the EM square for the font face. It is used by scalable
462 formats to scale design coordinates to device pixels, as described by the
463 last chapter of this section. Its value usually is 2048 (for TrueType)
464 or 1000 (for Type1), but others are possible too. It is set to 1 for
465 fixed-size formats like FNT/FON/PCF/BDF.</p>
466 </td></tr><tr valign=top><td>
467 <tt><b>global_bbox</b></tt>
469 <p>The global bounding box is defined as the largest rectangle that can
470 enclose all the glyphs in a font face. It is defined for horizontal
472 </td></tr><tr valign=top><td>
473 <tt><b>ascender</b></tt>
475 <p>The ascender is the vertical distance from the horizontal baseline to
476 the highest "character" coordinate in a font face. <em>Unfortunately, font
477 formats define the ascender differently</em>. For some, it represents
478 the ascent of all capital latin characters, without accents, for others
479 it's the ascent of the highest accented character, and finally, other
480 formats define it as being equal to <tt>global_bbox.yMax</tt>.</p>
481 </td></tr><tr valign=top><td>
482 <tt><b>descender</b></tt>
484 <p>The descender is the vertical distance from the horizontal baseline to
485 the lowest "character" coordinate in a font face. <em>Unfortunately, font
486 formats define the descender differently</em>. For some, it represents
487 the descent of all capital latin characters, without accents, for others
488 it's the ascent of the lowest accented character, and finally, other
489 formats define it as being equal to <tt>global_bbox.yMin</tt>.
490 <em><b>This field is usually negative</b></em></p>
491 </td></tr><tr valign=top><td>
492 <tt><b>text_height</b></tt>
494 <p>This field is simply used to compute a default line spacing (i.e. the
495 baseline-to-baseline distance) when writing text with this font. Note that
496 it usually is larger than the sum of the ascender and descender taken in
497 absolute value. There is also no guarantee that no glyphs can extend
498 above or below subsequent baselines when using this distance.</p>
499 </td></tr><tr valign=top><td>
500 <tt><b>max_advance_width</b></tt>
502 <p>This field gives the maximum horizontal cursor advance for all glyphs
503 in the font. It can be used to quickly compute the maximum advance width
504 of a string of text. <em>It doesn't correspond to the maximum glyph image
506 </td></tr><tr valign=top><td>
507 <tt><b>max_advance_height</b></tt>
509 <p>Same as <tt>max_advance_width</tt> but for vertical text layout. It is
510 only available in fonts providing vertical glyph metrics.</p>
511 </td></tr><tr valign=top><td>
512 <tt><b>underline_position</b></tt>
514 <p>When displaying or rendering underlined text, this value corresponds to
515 the vertical position, relative to the baseline, of the underline bar. It
516 noramlly is negative (as it's below the baseline).</p>
517 </td></tr><tr valign=top><td>
518 <tt><b>underline_thickness</b></tt>
520 <p>When displaying or rendering underlined text, this value corresponds to
521 the vertical thickness of the underline.</p>
522 </td></tr></table></center>
524 <p>Notice how, unfortunately, the values of the ascender and the descender
525 are not reliable (due to various discrepancies in font formats).</p>
528 b. Scaled Global Metrics:
531 <p>Each size object also contains a scaled versions of some of the global
532 metrics described above. They can be accessed directly through the
533 <tt><b>face->size->metrics</b></tt> structure.</p>
535 <p>Note that these values correspond to scaled versions of the design
536 global metrics, <em>with no rounding/grid-fitting performed.</em>.
537 They are also completely independent of any hinting process. In other
538 words, don't rely on them to get exact metrics at the pixel level.
539 They're expressed in 26.6 pixels.</p>
541 <center><table width="80%" cellpadding=5><tr valign=top><td>
542 <b><tt>ascender</tt></b>
544 <p>This is the scaled version of the original design ascender.</p>
545 </td></tr><tr valign=top><td>
546 <b><tt>descender</tt></b>
548 <p>This is the scaled version of the original design descender.</p>
549 </td></tr><tr valign=top><td>
550 <b><tt>height</tt></b>
552 <p>This is the scaled version of the original design text height.
553 That probably is the only field you should really use in this structure.</p>
554 </td></tr><tr valign=top><td>
555 <b><tt>max_advance</tt></b>
557 <p>Thi is the scaled version of the original design max advance.</p>
558 </td></tr></table></center>
560 <p>Note that the <tt><b>face->size->metrics</b></tt> structure contains other
561 fields that are used to scale design coordinates to device space. They're
562 described, in the last chapter.</p>
568 <p>Kerning is the process of adjusting the position of two subsequent
569 glyph images in a string of text, in order to improve the general
570 appearance of text. Basically, it means that when the glyph for an
571 "A" is followed by the glyph for a "V", the space between them can
572 be slightly reduced to avoid extra "diagonal whitespace".</p>
574 <p>Note that in theory, kerning can happen both in the horizontal and
575 vertical direction between two glyphs; however, it only happens in
576 the horizontal direction in nearly all cases except really extreme
579 <p>Note all font formats contain kerning information. Instead, they sometimes
580 rely on an additional file that contains various glyph metrics, including
581 kerning, but no glyph images. A good example would be the Type 1 format,
582 where glyph images are stored in a file with extension ".pfa" or ".pfb",
583 and where kerning metrics can be found in an additional file with extension
584 ".afm" or ".pfm".</p>
586 <p>FreeType 2 allows you to deal with this, by providing the
587 <tt><b>FT_Attach_File</b></tt> and <tt><b>FT_Attach_Stream</b></tt> APIs.
588 Both functions are used to load additional metrics into a face object,
589 by reading them from an additional format-specific file. For example,
590 you could open a Type 1 font by doing the following:</p>
592 <pre><font color="blue">
593 error = FT_New_Face( library, "/usr/shared/fonts/cour.pfb", 0, &face );
596 error = FT_Attach_File( face, "/usr/shared/fonts/cour.afm" );
597 if (error) { .. could not read kerning and additional metrics .. }
600 <p>Note that <tt><b>FT_Attach_Stream</b></tt> is similar to
601 <tt><b>FT_Attach_File</b></tt> except that it doesn't take a C string
602 to name the extra file, but a <tt>FT_Stream</tt> handle. Also,
603 <em>reading a metrics file is in no way, mandatory</em>.</p>
605 <p>Finally, the file attachment APIs are very generic and can be used to
606 load any kind of extra information for a given face. The nature of the
607 additional content is entirely font format specific.</p>
609 <p>FreeType 2 allows you to retrieve the kerning information between
610 two glyphs through the <tt><b>FT_Get_Kerning</b></tt> function, whose
611 interface looks like:</p>
613 <pre><font color="blue">
616 error = FT_Get_Kerning( face, <font color="gray">// handle to face object</font>
617 left, <font color="gray">// left glyph index</font>
618 right, <font color="gray">// right glyph index</font>
619 <em>kerning_mode</em>, <font color="gray">// kerning mode</font>
620 &kerning ); <font color="gray">// target vector</font>
623 <p>As you see, the function takes a handle to a face object, the indices
624 of the left and right glyphs for which the kerning value is desired,
625 as well as an integer, called the "kerning mode", and a pointer to
626 a destination vector that receives the corresponding distances.</p>
628 <p>The kerning mode is very similar to the "bbox mode" described in a
629 previous chapter. It's a enumeration that indicates how the
630 kerning distances are expressed in the target vector.</p>
632 <p>The default value is <tt><b>ft_kerning_mode_default</b></tt> which
633 has value 0. It corresponds to kerning distances expressed in 26.6
634 grid-fitted pixels (which means that the values are multiples of 64).
635 For scalable formats, this means that the design kerning distance is
636 scaled then rounded.</p>
638 <p>The value <tt><b>ft_kerning_mode_unfitted</b></tt> corresponds to kerning
639 distances expressed in 26.6 unfitted pixels (i.e. that do not correspond
640 to integer coordinates). It's the design kerning distance that is simply
641 scaled without rounding.</p>
643 <p>Finally, the value <tt><b>ft_kerning_mode_unscaled</b></tt> is used to
644 return the design kerning distance, expressed in font units. You can
645 later scale it to device space using the computations explained in the
646 last chapter of this section.</p>
648 <p>Note that the "left" and "right" positions correspond to the <em>visual
649 order</em> of the glyphs in the string of text. This is important for
651 bi-directional text, or simply when writing right-to-left text..</p>
656 4. Simple text rendering: kerning + centering:
659 <p>In order to show off what we just learned, we will now show how to modify
660 the example code that was provided in section I to render a string of text,
661 and enhance it to support kerning and delayed rendering.</p>
667 <p>Adding support for kerning to our code is trivial, as long as we consider
668 that we're still dealing with a left-to-right script like Latin. We
669 simply need to retrieve the kerning distance between two glyphs in order
670 to alter the pen position appropriately. The code looks like:</p>
672 <font color="blue"><pre>
673 FT_GlyphSlot slot = face->glyph; // a small shortcut
679 .. initialise library ..
680 .. create face object ..
681 .. set character size ..
686 use_kerning = FT_HAS_KERNING(face);
689 for ( n = 0; n < num_chars; n++ )
691 <font color="gray">// convert character code to glyph index</font>
692 glyph_index = FT_Get_Char_Index( face, text[n] );
694 <font color="gray">// retrieve kerning distance and move pen position</font>
695 if ( use_kerning && previous && glyph_index )
699 FT_Get_Kerning( face, previous, glyph_index,
700 ft_kerning_mode_default, &delta );
702 pen_x += delta.x >> 6;
705 <font color="gray">// load glyph image into the slot (erase previous one)</font>
706 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER );
707 if (error) continue; <font color="gray">// ignore errors</font>
709 <font color="gray">// now, draw to our target surface</font>
710 my_draw_bitmap( &slot->bitmap,
711 pen_x + slot->bitmap_left,
712 pen_y - slot->bitmap_top );
714 <font color="gray">// increment pen position</font>
715 pen_x += slot->advance.x >> 6;
717 <font color="gray">// record current glyph index</font>
718 previous = glyph_index
722 <p>That's it. You'll notice that:</p>
726 As kerning is determined from glyph indices, we need to explicitely
727 convert our character code into a glyph index, then later call
728 <tt>FT_Load_Glyph</tt> instead of <tt>FT_Load_Char</tt>. No big
729 deal, if you ask me :-)
733 We use a boolean named <tt>use_kerning</tt> which is set with the
734 result of the macro <tt><b>FT_HAS_KERNING(face)</b></tt>. It's
735 certainly faster not to call <tt>FT_Get_Kerning</tt> when we know
736 that the font face does not contain kerning information.
740 We move the position of the pen <em>before</em> a new glyph is drawn.
744 We did initialize the variable <tt>previous</tt> with the value 0,
745 which always correspond to the "missing glyph" (also called
746 <tt>.notdef</tt> in the Postscript world). There is never any
747 kerning distance associated with this glyph.
751 We do not check the error code returned by <tt>FT_get_Kerning</tt>.
752 This is because the function always set the content of <tt>delta</tt>
753 to (0,0) when an error occurs.
757 <p>As you see, this is not terribly complex :-)</p>
763 <p>Our code begins to become interesting but it's still a bit too simple
764 for normal uses. For example, the position of the pen is determined
765 before we do the rendering when in a normal situation, you would want
766 to layout the text and measure it before computing its final position
767 (e.g. centering) or perform things like word-wrapping.</p>
769 <p>We're thus now going to decompose our text rendering function into two
770 distinct but successive parts: the first one will position individual
771 glyph images on the baseline, while the second one will render the
772 glyphs. As we'll see, this has many advantages.</p>
774 <p>We will thus start by storing individual glyph images, as well as their
775 position on the baseline. This can be done with code like:</p>
777 <font color="blue"><pre>
778 FT_GlyphSlot slot = face->glyph; <font color="gray">// a small shortcut</font>
784 FT_Glyph glyphs[ MAX_GLYPHS ]; <font color="gray">// glyph image</font>
785 FT_Vector pos [ MAX_GLYPHS ]; <font color="gray">// glyph position</font>
788 .. initialise library ..
789 .. create face object ..
790 .. set character size ..
792 pen_x = 0; <font color="gray">/* start at (0,0) !! */</font>
796 use_kerning = FT_HAS_KERNING(face);
799 for ( n = 0; n < num_chars; n++ )
801 <font color="gray">// convert character code to glyph index</font>
802 glyph_index = FT_Get_Char_Index( face, text[n] );
804 <font color="gray">// retrieve kerning distance and move pen position</font>
805 if ( use_kerning && previous && glyph_index )
809 FT_Get_Kerning( face, previous, glyph_index,
810 ft_kerning_mode_default, &delta );
812 pen_x += delta.x >> 6;
815 <font color="gray">// store current pen position</font>
816 pos[ num_glyphs ].x = pen_x;
817 pos[ num_glyphs ].y = pen_y;
819 <font color="gray">// load glyph image into the slot. DO NOT RENDER IT !!</font>
820 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );
821 if (error) continue; // ignore errors, jump to next glyph
823 <font color="gray">// extract glyph image and store it in our table</font>
824 error = FT_Get_Glyph( face->glyph, & glyphs[num_glyphs] );
825 if (error) continue; // ignore errors, jump to next glyph
827 <font color="gray">// increment pen position</font>
828 pen_x += slot->advance.x >> 6;
830 <font color="gray">// record current glyph index</font>
831 previous = glyph_index
833 <font color="gray">// increment number of glyphs</font>
838 <p>As you see, this is a very simple variation of our previous code
839 where we extract each glyph image from the slot, and store it, along
840 with the corresponding position, in our tables.</p>
842 <p>Note also that "pen_x" contains the total advance for the string of
843 text. We can now compute the bounding box of the text string with
844 a simple function like:</p>
847 <font color="blue"><pre>
848 void compute_string_bbox( FT_BBox *abbox )
852 <font color="gray">// initialise string bbox to "empty" values</font>
853 bbox.xMin = bbox.yMin = 32000;
854 bbox.xMax = bbox.yMax = -32000;
856 <font color="gray">// for each glyph image, compute its bounding box, translate it,
857 // and grow the string bbox</font>
858 for ( n = 0; n < num_glyphs; n++ )
862 FT_Glyph_Get_CBox( glyphs[n], &glyph_bbox );
864 glyph_bbox.xMin += pos[n].x;
865 glyph_bbox.xMax += pos[n].x;
866 glyph_bbox.yMin += pos[n].y;
867 glyph_bbox.yMax += pos[n].y;
869 if (glyph_bbox.xMin < bbox.xMin)
870 bbox.xMin = glyph_bbox.xMin;
872 if (glyph_bbox.yMin < bbox.yMin)
873 bbox.yMin = glyph_bbox.yMin;
875 if (glyph_bbox.xMax > bbox.xMax)
876 bbox.xMax = glyph_bbox.xMax;
878 if (glyph_bbox.yMax &gy; bbox.yMax)
879 bbox.yMax = glyph_bbox.yMax;
882 <font color="gray">// check that we really grew the string bbox</font>
883 if ( bbox.xMin > bbox.xMax )
891 <font color="gray">// return string bbox</font>
896 <p>The resulting bounding box dimensions can then be used to compute the
897 final pen position before rendering the string as in:</p>
899 <font color="blue"><pre>
900 <font color="gray">// compute string dimensions in integer pixels</font>
901 string_width = (string_bbox.xMax - string_bbox.xMin)/64;
902 string_height = (string_bbox.yMax - string_bbox.yMin)/64;
904 <font color="gray">// compute start pen position in 26.6 cartesian pixels</font>
905 start_x = (( my_target_width - string_width )/2)*64;
906 start_y = (( my_target_height - string_height)/2)*64;
908 for ( n = 0; n < num_glyphs; n++ )
915 pen.x = start_x + pos[n].x;
916 pen.y = start_y + pos[n].y;
918 error = FT_Glyph_To_Bitmap( &image, ft_render_mode_normal,
922 FT_BitmapGlyph bit = (FT_BitmapGlyph)image;
924 my_draw_bitmap( bitmap->bitmap,
926 my_target_height - bitmap->top );
928 FT_Done_Glyph( image );
933 <p>You'll take note that:</p>
937 The pen position is expressed in the cartesian space (i.e. Y upwards).
941 We call <tt><b>FT_Glyph_To_Bitmap</b></tt> with the <tt>destroy</tt>
942 parameter set to 0 (false), in order to avoid destroying the original
943 glyph image. The new glyph bitmap is accessed through <tt>image</tt>
944 after the call and is typecasted to a <tt>FT_BitmapGlyph</tt>.
948 We use translation when calling <tt>FT_Glyph_To_Bitmap</tt>. This
949 ensures that the <tt><b>left</b></tt> and <tt><b>top</b></tt> fields
950 of the bitmap glyph object are already set to the correct pixel
951 coordinates in the cartesian space.
955 Of course, we still need to convert pixel coordinates from cartesian
956 to device space before rendering, hence the <tt>my_target_height -
957 bitmap->top</tt> in the call to <tt>my_draw_bitmap</tt>.
962 <p>The same loop can be used to render the string anywhere on our display
963 surface, without the need to reload our glyph images each time.. We
964 could also decide to implement word wrapping, and only draw</p>
968 5. Advanced text rendering: transform + centering + kerning:
971 <p>We are now going to modify our code in order to be able to easily
972 transform the rendered string, for example to rotate it. We will
973 start by performing a few minor improvements:</p>
975 <h4>a. packing & translating glyphs:</h4>
977 <p>We'll start by packing the information related to a single glyph image
978 into a single structure, instead of parallel arrays. We thus define the
979 following structure type:</p>
981 <font color="blue"><pre>
982 typedef struct TGlyph_
984 FT_UInt index; <font color="gray">// glyph index</font>
985 FT_Vector pos; <font color="gray">// glyph origin on the baseline</font>
986 FT_Glyph image; <font color="gray">// glyph image</font>
991 <p>We will also translate each glyph image directly after it is loaded
992 to its position on the baseline at load time. As we'll see, this
993 as several advantages. Our glyph sequence loader thus becomes:</p>
995 <font color="blue"><pre>
996 FT_GlyphSlot slot = face->glyph; <font color="gray">// a small shortcut</font>
1000 int pen_x, pen_y, n;
1002 TGlyph glyphs[ MAX_GLYPHS ]; <font color="gray">// glyphs table</font>
1003 PGlyph glyph; <font color="gray">// current glyph in table</font>
1006 .. initialise library ..
1007 .. create face object ..
1008 .. set character size ..
1010 pen_x = 0; <font color="gray">/* start at (0,0) !! */</font>
1014 use_kerning = FT_HAS_KERNING(face);
1018 for ( n = 0; n < num_chars; n++ )
1020 glyph->index = FT_Get_Char_Index( face, text[n] );
1022 if ( use_kerning && previous && glyph->index )
1026 FT_Get_Kerning( face, previous, glyph->index,
1027 ft_kerning_mode_default, &delta );
1029 pen_x += delta.x >> 6;
1032 <font color="gray">// store current pen position</font>
1033 glyph->pos.x = pen_x;
1034 glyph->pos.y = pen_y;
1036 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );
1037 if (error) continue;
1039 error = FT_Get_Glyph( face->glyph, &glyph->image );
1040 if (error) continue;
1042 <font color="gray">// translate the glyph image now..</font>
1043 FT_Glyph_Transform( glyph->image, 0, &glyph->pos );
1045 pen_x += slot->advance.x >> 6;
1046 previous = glyph->index
1048 <font color="gray">// increment number of glyphs</font>
1051 <font color="gray">// count number of glyphs loaded..</font>
1052 num_glyphs = glyph - glyphs;
1055 <p>Note that translating glyphs now has several advantages. The first
1056 one, is that we don't need to translate the glyph bbox when we compute
1057 the string's bounding box. The code becomes:</p>
1059 <font color="blue"><pre>
1060 void compute_string_bbox( FT_BBox *abbox )
1064 bbox.xMin = bbox.yMin = 32000;
1065 bbox.xMax = bbox.yMax = -32000;
1067 for ( n = 0; n < num_glyphs; n++ )
1071 FT_Glyph_Get_CBox( glyphs[n], &glyph_bbox );
1073 if (glyph_bbox.xMin < bbox.xMin)
1074 bbox.xMin = glyph_bbox.xMin;
1076 if (glyph_bbox.yMin < bbox.yMin)
1077 bbox.yMin = glyph_bbox.yMin;
1079 if (glyph_bbox.xMax > bbox.xMax)
1080 bbox.xMax = glyph_bbox.xMax;
1082 if (glyph_bbox.yMax &gy; bbox.yMax)
1083 bbox.yMax = glyph_bbox.yMax;
1086 if ( bbox.xMin > bbox.xMax )
1098 <p>Now take a closer look, the <tt>compute_string_bbox</tt> can now
1099 compute the bounding box of a transformed glyph string. For example,
1100 we can do something like:</p>
1102 <pre><font color="blue">
1107 ... load glyph sequence
1109 ... setup "matrix" and "delta"
1111 <font color="gray">// transform glyphs</font>
1112 for ( n = 0; n < num_glyphs; n++ )
1113 FT_Glyph_Transform( glyphs[n].image, &matrix, &delta );
1115 <font color="gray">// compute bounding box of transformed glyphs</font>
1116 compute_string_bbox( &bbox );
1120 b. Rendering a transformed glyph sequence:
1123 <p>However, directly transforming the glyphs in our sequence is not an idea
1124 if we want to re-use them in order to draw the text string with various
1125 angles or transforms. It's better to perform the affine transformation
1126 just before the glyph is rendered, as in the following code:</p>
1128 <font color="blue"><pre>
1130 FT_Matrix transform;
1132 <font color="gray">// get bbox of original glyph sequence</font>
1133 compute_string_bbox( &string_bbox );
1135 <font color="gray">// compute string dimensions in integer pixels</font>
1136 string_width = (string_bbox.xMax - string_bbox.xMin)/64;
1137 string_height = (string_bbox.yMax - string_bbox.yMin)/64;
1139 <font color="gray">// set up start position in 26.6 cartesian space</font>
1140 start.x = (( my_target_width - string_width )/2)*64;
1141 start.y = (( my_target_height - string_height)/2)*64;
1143 <font color="gray">// set up transform (a rotation here)</font>
1144 matrix.xx = (FT_Fixed)( cos(angle)*0x10000);
1145 matrix.xy = (FT_Fixed)(-sin(angle)*0x10000);
1146 matrix.yx = (FT_Fixed)( sin(angle)*0x10000);
1147 matrix.yy = (FT_Fixed)( cos(angle)*0x10000);
1149 for ( n = 0; n < num_glyphs; n++ )
1155 <font color="gray">// create a copy of the original glyph</font>
1156 error = FT_Glyph_Copy( glyphs[n].image, &image );
1157 if (error) continue;
1159 <font color="gray">// transform copy (this will also translate it to the correct
1161 FT_Glyph_Transform( image, &matrix, &start );
1163 <font color="gray">// check bounding box, if the transformed glyph image
1164 // is not in our target surface, we can avoid rendering it</font>
1165 FT_Glyph_Get_CBox( image, ft_glyph_bbox_pixels, &bbox );
1166 if ( bbox.xMax <= 0 || bbox.xMin >= my_target_width ||
1167 bbox.yMax <= 0 || bbox.yMin >= my_target_height )
1170 <font color="gray">// convert glyph image to bitmap (destroy the glyph copy !!)
1172 error = FT_Glyph_To_Bitmap( &image,
1173 ft_render_mode_normal,
1174 0, <font color="gray">// no additional translation</font>
1175 1 ); <font color="gray">// destroy copy in "image"</font>
1178 FT_BitmapGlyph bit = (FT_BitmapGlyph)image;
1180 my_draw_bitmap( bitmap->bitmap,
1182 my_target_height - bitmap->top );
1184 FT_Done_Glyph( image );
1189 <p>You'll notice a few changes compared to the original version of this
1194 We keep the original glyph images untouched, by transforming a
1199 We perform clipping computations, in order to avoid rendering &
1200 drawing glyphs that are not within our target surface
1204 We always destroy the copy when calling <tt>FT_Glyph_To_Bitmap</tt>
1205 in order to get rid of the transformed scalable image. Note that
1206 the image is destroyed even when the function returns an error
1207 code (which is why <tt>FT_Done_Glyph</tt> is only called within
1208 the compound statement.
1212 The translation of the glyph sequence to the start pen position is
1213 integrated in the call to <tt>FT_Glyph_Transform</tt> intead of
1214 <tt>FT_Glyph_To_Bitmap</tt>.
1218 <p>It's possible to call this function several times to render the string
1219 width different angles, or even change the way "start" is computed in
1220 order to move it to different place.</p>
1222 <p>This code is the basis of the FreeType 2 demonstration program
1223 named"<tt>ftstring.c</tt>". It could be easily extended to perform
1224 advanced text layout or word-wrapping in the first part, without
1225 changing the second one.</p>
1227 <p>Note however that a normal implementation would use a glyph cache in
1228 order to reduce memory needs. For example, let's assume that our text
1229 string is "FreeType". We would store three identical glyph images in
1230 our table for the letter "e", which isn't optimal (especially when you
1231 consider longer lines of text, or even whole pages..).
1237 6. Accessing metrics in design font units, and scaling them:
1240 <p>Scalable font formats usually store a single vectorial image, called
1241 an "outline", for each in a face. Each outline is defined in an abstract
1242 grid called the "design space", with coordinates expressed in nominal
1243 "font units". When a glyph image is loaded, the font driver usually
1244 scales the outline to device space according to the current character
1245 pixel size found in a <tt>FT_Size</tt> object. The driver may also
1246 modify the scaled outline in order to significantly improve its
1247 appearance on a pixel-based surface (a process known as "hinting"
1248 or "grid-fitting").</p>
1250 <p>This chapter describes how design coordinates are scaled to device
1251 space, and how to read glyph outlines and metrics in font units. This
1252 is important for a number of things:</p>
1256 In order to perform "true" WYSIWYG text layout
1260 In order to access font content for conversion or analysis purposes
1264 <h4>a.Scaling distances to device space:</h4>
1266 <p>Design coordinates are scaled to device space using a simple scaling
1267 transform, whose coefficients are computed with the help of the
1268 <em><b>character pixel size</b></em>:</p>
1270 <pre><font color="purple">
1271 device_x = design_x * x_scale
1272 device_y = design_y * y_scale
1274 x_scale = pixel_size_x / EM_size
1275 y_scale = pixel_size_y / EM_size
1278 <p>Here, the value <b><tt>EM_size</tt></b> is font-specific and correspond
1279 to the size of an abstract square of the design space (called the "EM"),
1280 which is used by font designers to create glyph images. It is thus
1281 expressed in font units. It is also accessible directly for scalable
1282 font formats as <tt><b>face->units_per_EM</b></tt>. You should
1283 check that a font face contains scalable glyph images by using the
1284 <tt><b>FT_IS_SCALABLE(face)</b></tt> macro, which returns true when
1287 <p>When you call the function <tt><b>FT_Set_Pixel_Sizes</b></tt>, you're
1288 specifying the value of <tt>pixel_size_x</tt> and <tt>pixel_size_y</tt>
1289 you want to use to FreeType, which will immediately compute the values
1290 of <tt>x_scale</tt> and <tt>y_scale</tt>.</p>
1292 <p>When you call the function <tt><b>FT_Set_Char_Size</b></tt>, you're
1293 specifying the character size in physical "points", which is used,
1294 along with the device's resolutions, to compute the character pixel
1295 size, then the scaling factors.</p>
1297 <p>Note that after calling any of these two functions, you can access
1298 the values of the character pixel size and scaling factors as fields
1299 of the <tt><b>face->size->metrics</b></tt> structure. These fields are:</p>
1302 <table width="80%" cellpadding="5"><tr valign=top><td>
1303 <b><tt>x_ppem</t></b>
1305 <p>Which stands for "X Pixels Per EM", this is the size in integer pixels
1306 of the EM square, which also is the <em>horizontal character pixel size</em>,
1307 called <tt>pixel_size_x</tt> in the above example.</p>
1308 </td></tr><tr valign=top><td>
1309 <b><tt>y_ppem</tt></b>
1311 <p>Which stands for "Y Pixels Per EM", this is the size in integer pixels
1312 of the EM square, which also is the <em>vertical character pixel size</em>,
1313 called <tt>pixel_size_y</tt> in the above example.</p>
1314 </td></tr><tr valign=top><td>
1315 <b><tt>x_scale</tt></b>
1317 <p>This is a 16.16 fixed float scale that is used to directly
1318 scale horizontal distances from design space to 1/64th of device pixels.
1320 </td></tr><tr valign=top><td>
1321 <b><tt>y_scale</tt></b>
1323 <p>This is a 16.16 fixed float scale that is used to directly scale
1324 vertical distances from design space to 1/64th of device pixels.</p>
1329 <p>Basically, this means that you can scale a distance expressed in
1330 font units to 26.6 pixels directly with the help of the <tt>FT_MulFix</tt>
1331 function, as in:</p>
1333 <pre><font color="blue">
1334 <font color="gray">// convert design distances to 1/64th of pixels
1336 pixels_x = FT_MulFix( design_x, face->size->metrics.x_scale );
1337 pixels_y = FT_MulFix( design_y, face->size->metrics.y_scale );
1340 <p>However, you can also scale the value directly with more accuracy
1341 by using doubles and the equations:</p>
1343 <pre><font color="blue">
1344 FT_Size_Metrics* metrics = &face->size->metrics; // shortcut
1345 double pixels_x, pixels_y;
1346 double em_size, x_scale, y_scale;
1348 <font color="gray">// compute floating point scale factors
1350 em_size = 1.0 * face->units_per_EM;
1351 x_scale = metrics->x_ppem / em_size;
1352 y_scale = metrics->y_ppem / em_size;
1354 <font color="gray">// convert design distances to floating point pixels
1356 pixels_x = design_x * x_scale;
1357 pixels_y = design_y * y_scale;
1361 b. Accessing design metrics (glyph & global):
1364 <p>You can access glyph metrics in font units simply by specifying the
1365 <tt><b>FT_LOAD_NO_SCALE</b></tt> bit flag in <tt>FT_Load_Glyph</tt>
1366 or <tt>FT_Load_Char</tt>. The metrics returned in
1367 <tt>face->glyph->metrics</tt> will all be in font units.</p>
1369 <p>You can access unscaled kerning data using the
1370 <tt><b>ft_kerning_mode_unscaled</b></tt> mode</p>
1372 <p>Finally, a few global metrics are available directly in font units
1373 as fields of the <tt>FT_Face</tt> handle, as described in chapter 3
1374 of this section.</p>
1382 <p>This is the end of the second section of the FreeType 2 tutorial,
1383 you're now able to access glyph metrics, manage glyph images, and
1384 render text much more intelligently (kerning, measuring, transforming
1387 <p>You have now sufficient knowledge to build a pretty decent text service
1388 on top of FreeType 2, and you could possibly stop there if you want.</p>
1390 <p>The next section will deal with FreeType 2 internals (like modules,
1391 vector outlines, font drivers, renderers), as well as a few font format
1392 specific issues (mainly, how to access certain TrueType or Type 1 tables).