Debian Codegraph @

ft2docs/docs/tutorial/step2.html

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
2 "http://www.w3.org/TR/html4/loose.dtd">
3
4 <html lang="en">
5
6 <head>
7 <meta http-equiv="Content-Type"
8 content="text/html; charset=utf-8">
9 <meta http-equiv="Content-Style-Type"
10 content="text/css">
11 <meta http-equiv="Content-Script-Type"
12 content="text/javascript">
13 <meta name="description"
14 content="FreeType Documentation">
15 <meta name="Author"
16 content="David Turner">
17
18 <link rel="icon"
19 href="../image/favicon_-90.ico">
20 <link rel="shortcut icon"
21 href="../image/favicon_-90.ico">
22 <link rel="stylesheet"
23 type="text/css"
24 href="../css/freetype2_-90.css">
25
26 <script type="text/javascript"
27 src="../../../js/freetype2.js">
28 </script>
29
30 <title>FreeType Tutorial / II</title>
31 </head>
32
33
34 <body>
35
36 <div id="top"
37 class="bar">
38 <h1><a href="http://freetype.org/index.html">FreeType</a>
39 Tutorial&nbsp;/&nbsp;II</h1>
40 </div>
41
42
43 <div id="wrapper">
44
45 <div class="colmask leftmenu">
46 <div class="colright">
47 <div class="col1wrap">
48 <div class="col1">
49
50
51 <!-- ************************************************** -->
52
53 <div id="simple-glyph-loading">
54 <h2>II. Managing Glyphs</h2>
55
56
57 <h3 id="section-1">1. Glyph Metrics</h3>
58
59 <p>Glyph metrics are, as the name suggests, certain
60 distances associated with each glyph that describe how to
61 position this glyph while creating a text layout.</p>
62
63 <p>There are usually two sets of metrics for a single glyph:
64 Those used to represent glyphs in horizontal text layouts
65 (Latin, Cyrillic, Arabic, Hebrew, etc.), and those used to
66 represent glyphs in vertical text layouts (Chinese,
67 Japanese, Korean, Mongolian, etc.).</p>
68
69 <p>Note that only a few font formats provide vertical
70 metrics. You can test whether a given face object
71 contains them by using the
72 macro <a href="../reference/ft2-font_testing_macros.html#ft_has_vertical"><code>FT_HAS_VERTICAL</code></a>,
73 which returns true if appropriate.</p>
74
75 <p>Individual glyph metrics can be accessed by first loading
76 the glyph in a face's glyph slot, then accessing them
77 through the <code>face-&gt;glyph-&gt;metrics</code>
78 structure, whose type
79 is <a href="../reference/ft2-glyph_retrieval.html#ft_glyph_metrics"><code>FT_Glyph_Metrics</code></a>.
80 We will discuss this in more detail below; for now, we
81 only note that it contains the following fields.</p>
82
83 <dl>
84 <dt>width</dt>
85 <dd>This is the width of the glyph image's bounding box.
86 It is independent of the layout direction.</dd>
87
88 <dt>height</dt>
89 <dd>This is the height of the glyph image's bounding box.
90 It is independent of the layout direction. Be careful
91 not to confuse it with the &lsquo;height&rsquo; field in
92 the <a href="../reference/ft2-sizing_and_scaling.html#ft_size_metrics">
93 <code>FT_Size_Metrics</code></a> structure.</dd>
94
95 <dt>horiBearingX</dt>
96 <dd>For <em>horizontal text layouts</em>, this is the
97 horizontal distance from the current cursor position to
98 the leftmost border of the glyph image's bounding
99 box.</dd>
100
101 <dt>horiBearingY</dt>
102 <dd>For <em>horizontal text layouts</em>, this is the
103 vertical distance from the current cursor position (on
104 the baseline) to the topmost border of the glyph image's
105 bounding box.</dd>
106
107 <dt>horiAdvance</dt>
108 <dd>For <em>horizontal text layouts</em>, this is the
109 horizontal distance to increment the pen position when
110 the glyph is drawn as part of a string of text.</dd>
111
112 <dt>vertBearingX</dt>
113 <dd>For <em>vertical text layouts</em>, this is the
114 horizontal distance from the current cursor position to
115 the leftmost border of the glyph image's bounding
116 box.</dd>
117
118 <dt>vertBearingY</dt>
119 <dd>For <em>vertical text layouts</em>, this is the
120 vertical distance from the current cursor position (on
121 the baseline) to the topmost border of the glyph image's
122 bounding box.</dd>
123
124 <dt>vertAdvance</dt>
125 <dd>For <em>vertical text layouts</em>, this is the
126 vertical distance used to increment the pen position
127 when the glyph is drawn as part of a string of
128 text.</dd>
129 </dl>
130
131 <p class="warning">As not all fonts do contain vertical
132 metrics, the values of <code>vertBearingX</code>,
133 <code>vertBearingY</code> and <code>vertAdvance</code>
134 should not be considered reliable
135 if <code>FT_HAS_VERTICAL</code> returns false.</p>
136
137 <p>The following graphics illustrate the metrics more
138 clearly. In case a distance is directed, it is marked
139 with a single arrow, indicating a positive value. The
140 first image displays horizontal metrics, where the
141 baseline is the horizontal axis.</p>
142
143 <div class="figure">
144 <img src="glyph-metrics-3.svg"
145 alt="horizontal layout"
146 width="45%"
147 height="45%">
148 </div>
149
150 <p>For vertical text layouts, the baseline is vertical,
151 identical to the vertical axis. Contrary to all other
152 arrows, <code>bearingX</code> shows a negative value in
153 this image.</p>
154
155 <div class="figure">
156 <img src="glyph-metrics-4.svg"
157 alt="vertical layout"
158 width="40%"
159 height="40%">
160 </div>
161
162 <p>The metrics found
163 in <code>face-&gt;glyph-&gt;metrics</code> are normally
164 expressed in 26.6 pixel format (i.e., 1/64 of pixels),
165 unless you use the <code>FT_LOAD_NO_SCALE</code> flag when
166 calling <code>FT_Load_Glyph</code>
167 or <code>FT_Load_Char</code>. In this case, the metrics
168 are expressed in original font units.</p>
169
170 <p>The glyph slot object has also a few other interesting
171 fields that eases a developer's work. You can access them
172 through <code>face-&gt;glyph-&gt;xxx</code>,
173 where <code>xxx</code> is one of the following fields.</p>
174
175 <dl>
176 <dt>advance</dt>
177 <dd>This field is a <code>FT_Vector</code> that holds the
178 transformed advance for the glyph. That is useful when
179 you are using a transformation
180 through <code>FT_Set_Transform</code>, as shown in the
181 <a href="step1.html#transformed-text">rotated text
182 example</a> of part&nbsp;I. Other than that, its value
183 is by default (metrics.horiAdvance,0), unless you
184 specify <code>FT_LOAD_VERTICAL</code> when loading the
185 glyph image; it is then (0,metrics.vertAdvance).</dd>
186
187 <dt>linearHoriAdvance</dt>
188 <dd>This field contains the linearly scaled value of the
189 glyph's horizontal advance width. Indeed, the value of
190 <code>metrics.horiAdvance</code> that is returned in the
191 glyph slot is normally rounded to integer pixel
192 coordinates (i.e., being a multiple of&nbsp;64) by the
193 font driver that actually loads the glyph
194 image. <code>linearHoriAdvance</code> is a 16.16
195 fixed-point number that gives the value of the original
196 glyph advance width in 1/65536 of pixels. It can be use
197 to perform pseudo device-independent text layouts.</dd>
198
199 <dt>linearVertAdvance</dt>
200 <dd>This is the similar to <code>linearHoriAdvance</code>
201 but for the glyph's vertical advance height. Its value
202 is only reliable if the font face contains vertical
203 metrics.</dd>
204 </dl>
205
206
207 <h3 id="section-2">2. Managing Glyph Images</h3>
208
209 <p>The glyph image that is loaded in a glyph slot can be
210 converted into a bitmap, either by
211 using <code>FT_LOAD_RENDER</code> when loading it, or by
212 calling <a href="../reference/ft2-glyph_retrieval.html#ft_render_glyph"><code>FT_Render_Glyph</code></a>.
213 Each time you load a new glyph image, the previous one is
214 erased from the glyph slot.</p>
215
216 <p>There are situations, however, where you may need to
217 extract this image from the glyph slot in order to cache
218 it within your application, and even perform additional
219 transformations and measures on it before converting it to
220 a bitmap.</p>
221
222 <p>The FreeType&nbsp;2 API has a specific extension that is
223 capable of dealing with glyph images in a flexible and
224 generic way. To use it, you first need to include
225 the <a href="../reference/ft2-header_file_macros.html#ft_glyph_h"><code>FT_GLYPH_H</code></a>
226 header file.</p>
227
228 <pre>
229 #include FT_GLYPH_H</pre>
230
231 <h4>a.Extracting the Glyph Image</h4>
232
233 <p>You can extract a single glyph image very easily. Here
234 some code that shows how to do it.</p>
235
236 <pre>
237 FT_Glyph glyph; <span class="comment">/* a handle to the glyph image */</span>
238
239
240 ...
241 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_NORMAL );
242 if ( error ) { ... }
243
244 error = FT_Get_Glyph( face-&gt;glyph, &amp;glyph );
245 if ( error ) { ... }</pre>
246
247 <p>The following steps are performed.</p>
248
249 <ul>
250 <li>Create a variable named <code>glyph</code>, of
251 type <a href="../reference/ft2-glyph_management.html#ft_glyph"><code>FT_Glyph</code></a>.
252 This is a handle (pointer) to an individual glyph
253 image.</li>
254
255 <li>Load the glyph image in the normal way into the face's
256 glyph slot. We don't use <code>FT_LOAD_RENDER</code>
257 because we want to grab a scalable glyph image that we
258 can transform later on.</li>
259
260 <li>Copy the glyph image from the slot into a
261 new <code>FT_Glyph</code> object by
262 calling <a href="../reference/ft2-glyph_management.html#ft_get_glyph"><code>FT_Get_Glyph</code></a>.
263 This function returns an error code and
264 sets <code>glyph</code>.</li>
265 </ul>
266
267 <p>It is important to note that the extracted glyph is in
268 the same format as the original one that is still in the
269 slot. For example, if we are loading a glyph from a
270 TrueType font file, the glyph image is really a scalable
271 vector outline. You can access the
272 field <code>glyph-&gt;format</code> if you want to know
273 exactly how the glyph is modeled and stored.</p>
274
275 <p>A new glyph object can be destroyed with a call
276 to <a href="../reference/ft2-glyph_management.html#ft_done_glyph"><code>FT_Done_Glyph</code></a>.</p>
277
278 <p>The glyph object contains exactly one glyph image and a
279 2D vector representing the glyph's advance in 16.16
280 fixed-point coordinates. The latter can be accessed
281 directly as <code>glyph-&gt;advance</code></p>
282
283 <p class="warning">Note that unlike other FreeType objects,
284 the library doesn't keep a list of all allocated glyph
285 objects. This means you have to destroy them yourself
286 instead of relying on <code>FT_Done_FreeType</code> doing
287 all the clean-up.</p>
288
289 <h4>b. Transforming &amp; Copying the Glyph Image</h4>
290
291 <p>If the glyph image is scalable (i.e.,
292 if <code>glyph-&gt;format</code> is not equal
293 to <code>FT_GLYPH_FORMAT_BITMAP</code>), it is possible to
294 transform the image anytime by a call
295 to <a href="../reference/ft2-glyph_management.html#ft_glyph_transform"><code>FT_Glyph_Transform</code></a>.</p>
296
297 <p>You can also copy a single glyph image
298 with <a href="../reference/ft2-glyph_management.html#ft_glyph_copy"><code>FT_Glyph_Copy</code></a>.</p>
299
300 <pre>
301 FT_Glyph glyph, glyph2;
302 FT_Matrix matrix;
303 FT_Vector delta;
304
305
306 ... load glyph image in `glyph' ...
307
308 <span class="comment">/* copy glyph to glyph2 */</span>
309
310 error = FT_Glyph_Copy( glyph, &amp;glyph2 );
311 if ( error ) { ... could not copy (out of memory) ... }
312
313 <span class="comment">/* translate `glyph' */</span>
314
315 delta.x = -100 * 64; <span class="comment">/* coordinates are in 26.6 pixel format */</span>
316 delta.y = 50 * 64;
317
318 FT_Glyph_Transform( glyph, 0, &amp;delta );
319
320 <span class="comment">/* transform glyph2 (horizontal shear) */</span>
321
322 matrix.xx = 0x10000L;
323 matrix.xy = 0.12 * 0x10000L;
324 matrix.yx = 0;
325 matrix.yy = 0x10000L;
326
327 FT_Glyph_Transform( glyph2, &amp;matrix, 0 );</pre>
328
329 <p>Note that the 2&times;2 transformation matrix is always
330 applied to the 16.16 advance vector in the glyph; you thus
331 don't need to recompute it.</p>
332
333 <h4>c. Measuring the Glyph Image</h4>
334
335 <p>You can also retrieve the control (bounding) box of any
336 glyph image (scalable or not) through
337 the <a href="../reference/ft2-glyph_management.html#ft_glyph_get_cbox"><code>FT_Glyph_Get_CBox</code></a>
338 function.</p>
339
340 <pre>
341 FT_BBox bbox;
342
343
344 ...
345 FT_Glyph_Get_CBox( glyph, <em>bbox_mode</em>, &amp;bbox );</pre>
346
347 <p>Coordinates are relative to the glyph origin (0,0), using
348 the y&nbsp;upwards convention. This function takes a
349 special argument, the <em>bbox mode</em>, to indicate how
350 box coordinates are expressed.</p>
351
352 <p>If the glyph has been loaded
353 with <code>FT_LOAD_NO_SCALE</code>, <code>bbox_mode</code>
354 must be set to <code>FT_GLYPH_BBOX_UNSCALED</code> to get
355 unscaled font units in 26.6 pixel format. The
356 value <code>FT_GLYPH_BBOX_SUBPIXELS</code> is another name
357 for this constant.</p>
358
359 <p>Note that the box's maximum coordinates are exclusive,
360 which means that you can always compute the width and
361 height of the glyph image (regardless of using integer or
362 26.6 coordinates) with a simple subtraction.</p>
363
364 <pre class="example">
365 width = bbox.xMax - bbox.xMin;
366 height = bbox.yMax - bbox.yMin;</pre>
367
368 <p>Note also that for 26.6 coordinates, if
369 <code>FT_GLYPH_BBOX_GRIDFIT</code> is used as the bbox
370 mode, the coordinates are also grid-fitted, which
371 corresponds to the following four lines of
372 pseudo-code.</p>
373
374 <pre class="example">
375 bbox.xMin = FLOOR( bbox.xMin )
376 bbox.yMin = FLOOR( bbox.yMin )
377 bbox.xMax = CEILING( bbox.xMax )
378 bbox.yMax = CEILING( bbox.yMax )</pre>
379
380 <p>To get the bbox in <em>integer</em> pixel coordinates,
381 set <code>bbox_mode</code>
382 to <code>FT_GLYPH_BBOX_TRUNCATE</code>.</p>
383
384 <p>Finally, to get the bounding box in grid-fitted pixel
385 coordinates, set <code>bbox_mode</code>
386 to <code>FT_GLYPH_BBOX_PIXELS</code>.</p>
387
388 <p>[Computing <em>exact</em> bounding boxes can be done with
389 function <a href="../reference/ft2-outline_processing.html#ft_outline_get_bbox"><code>FT_Outline_Get_BBox</code></a>,
390 at the cost of slower execution. You probably don't need
391 it with the possible exception of rotated glyphs.]</p>
392
393 <h4>d. Converting the Glyph Image to a Bitmap</h4>
394
395 <p>You may need to convert the glyph object to a bitmap once
396 you have conveniently cached or transformed it. This can
397 be done easily with
398 the <a href="../reference/ft2-glyph_management.html"><code>FT_Glyph_To_Bitmap</code></a>
399 function, which handles any glyph object.</p>
400
401 <pre>
402 FT_Vector origin;
403
404
405 origin.x = 32; <span class="comment">/* 1/2 pixel in 26.6 format */</span>
406 origin.y = 0;
407
408 error = FT_Glyph_To_Bitmap(
409 &amp;glyph,
410 <em>render_mode</em>,
411 &amp;origin,
412 1 ); <span class="comment">/* destroy original image == true */</span></pre>
413
414 <p>Some notes.</p>
415
416 <ul>
417 <li>The first parameter is the address of the source
418 glyph's handle. When the function is called, it reads
419 it to access the source glyph object. After the call,
420 the handle points to a <em>new</em> glyph object that
421 contains the rendered bitmap.</li>
422
423 <li>The second parameter is a standard render mode to
424 specify what kind of bitmap we want. For example, it
425 can be <code>FT_RENDER_MODE_DEFAULT</code> for an 8-bit
426 anti-aliased pixmap, or <code>FT_RENDER_MODE_MONO</code>
427 for a 1-bit monochrome bitmap.</li>
428
429 <li>The third parameter is a pointer to a two-dimensional
430 vector to translate the source glyph image before the
431 conversion. After the call, the source image is
432 translated back to its original position (and is thus
433 left unchanged). If you do not need to translate the
434 source glyph before rendering, set this pointer
435 to NULL.</li>
436
437 <li>The last parameter is a boolean that indicates whether
438 the source glyph object should be destroyed by the
439 function. If false, the original glyph object is never
440 destroyed, even if its handle is lost (it is up to
441 client applications to keep it).</li>
442 </ul>
443
444 <p>The new glyph object always contains a bitmap (if no
445 error is returned), and you must <em>typecast</em> its
446 handle to the <code>FT_BitmapGlyph</code> type in order to
447 access its content. This type is a sort of
448 &lsquo;subclass&rsquo; of <code>FT_Glyph</code> that
449 contains additional fields
450 (see <a href="../reference/ft2-glyph_management.html#ft_bitmapglyphrec"><code>FT_BitmapGlyphRec</code></a>).</p>
451
452 <dl>
453 <dt>left</dt>
454 <dd>Just like the <code>bitmap_left</code> field of a
455 glyph slot, this is the horizontal distance from the
456 glyph origin (0,0) to the leftmost pixel of the glyph
457 bitmap. It is expressed in integer pixels.</dd>
458
459 <dt>top</dt>
460 <dd>Just like the <code>bitmap_top</code> field of a glyph
461 slot, this is the vertical distance from the glyph
462 origin (0,0) to the topmost pixel of the glyph bitmap
463 (more precise, to the pixel just above the bitmap).
464 This distance is expressed in integer pixels, and is
465 positive for upwards&nbsp;y.</dd>
466
467 <dt>bitmap</dt>
468 <dd>This is a bitmap descriptor for the glyph object, just
469 like the <code>bitmap</code> field in a glyph slot.</dd>
470 </dl>
471
472
473 <h3 id="section-3">3. Global Glyph Metrics</h3>
474
475 <p>Unlike glyph metrics, global metrics are used to describe
476 distances and features of a whole font face. They can be
477 expressed either in 26.6 pixel format or in (unscaled)
478 font units for scalable formats.</p>
479
480 <h4> a. Design global metrics</h4>
481
482 <p>For scalable formats, all global metrics are expressed in
483 font units in order to be later scaled to the device
484 space, according to the rules described in the last
485 section of this tutorial part. You can access them
486 directly as fields of an <code>FT_Face</code> handle.</p>
487
488 <p>However, you need to check that the font face's format is
489 scalable before using them. One can do it with
490 macro <code>FT_IS_SCALABLE</code>, which returns true when
491 appropriate.</p>
492
493 <p>Here a table of the global design metrics for scalable
494 faces.</p>
495
496 <dl>
497 <dt>units_per_EM</dt>
498 <dd>This is the size of the EM square for the font face.
499 It is used by scalable formats to scale design
500 coordinates to device pixels, as described in the last
501 section of this tutorial part. Its value usually is
502 2048 (for TrueType) or 1000 (for Type&nbsp;1 or CFF),
503 but other values are possible, too. It is set to&nbsp;1
504 for fixed-size formats like FNT, FON, PCF, or BDF.</dd>
505
506 <dt>bbox</dt>
507 <dd>The global bounding box is defined as the smallest
508 rectangle that can enclose all the glyphs in a font
509 face.</dd>
510
511 <dt>ascender</dt>
512 <dd>The ascender is the vertical distance from the
513 horizontal baseline to the highest
514 &lsquo;character&rsquo; coordinate in a font face.
515 Unfortunately, font formats don't define the ascender in
516 a uniform way. For some formats, it represents the
517 ascent of all capital latin characters (without
518 accents), for others it is the ascent of the highest
519 accented character, and finally, other formats define it
520 as being equal to <code>bbox.yMax</code>.</dd>
521
522 <dt>descender</dt>
523 <dd>The descender is the vertical distance from the
524 horizontal baseline to the lowest
525 &lsquo;character&rsquo; coordinate in a font face.
526 Unfortunately, font formats don't define the descender
527 in a uniform way. For some formats, it represents the
528 descent of all capital latin characters (without
529 accents), for others it is the ascent of the lowest
530 accented character, and finally, other formats define it
531 as being equal to <code>bbox.yMin</code>. This field is
532 negative for values below the baseline.</dd>
533
534 <dt>height</dt>
535 <dd>This field represents a <em>default line spacing</em>
536 (i.e., the baseline-to-baseline distance) when writing
537 text with this font. Note that it usually is larger
538 than the sum of the ascender and descender taken as
539 absolute values. There is also no guarantee that no
540 glyphs extend above or below subsequent baselines when
541 using this distance &ndash; think of it as a value the
542 designer of the font finds appropriate.</dd>
543
544 <dt>max_advance_width</dt>
545 <dd>This field gives the maximum horizontal cursor advance
546 for all glyphs in the font. It can be used to quickly
547 compute the maximum advance width of a string of
548 text. <em>It doesn't correspond to the maximum glyph
549 image width!</em></dd>
550
551 <dt>max_advance_height</dt>
552 <dd>Same as <code>max_advance_width</code> but for
553 vertical text layout.</dd>
554
555 <dt>underline_position</dt>
556 <dd>When displaying or rendering underlined text, this
557 value corresponds to the vertical position, relative to
558 the baseline, of the underline bar's center. It is
559 negative if it is below the baseline.</dd>
560
561 <dt>underline_thickness</dt>
562 <dd>When displaying or rendering underlined text, this
563 value corresponds to the vertical thickness of the
564 underline.</dd>
565 </dl>
566
567 <p>Notice that the values of the ascender and the descender
568 are not reliable (due to various discrepancies in font
569 formats), unfortunately.</p>
570
571 <h4>b. Scaled Global Metrics</h4>
572
573 <p>Each size object also contains a scaled version of some
574 of the global metrics described above, to be directly
575 accessed through
576 the <code>face-&gt;size-&gt;metrics</code> structure (of
577 type <a href="../reference/ft2-sizing_and_scaling.html#ft_size_metrics">
578 <code>FT_Size_Metrics</code></a>). <em>No grid-fitting
579 is performed for those values</em>. They are also
580 completely independent of any hinting process. In other
581 words, don't rely on them to get exact metrics at the
582 pixel level. They are expressed in 26.6 pixel format but
583 rounded for historical reasons.</p>
584
585 <dl>
586 <dt>ascender</dt>
587 <dd>The scaled version of the original design ascender;
588 rounded up to an integer value.</dd>
589
590 <dt>descender</dt>
591 <dd>The scaled version of the original design descender,
592 rounded down to an integer value.</dd>
593
594 <dt>height</dt>
595 <dd>
596 <p>The scaled version of the original design text height
597 (the vertical distance from one baseline to the next).
598 This is probably the only field you should really use
599 in this structure. It is rounded to an integer
600 value.</p>
601
602 <p>Be careful not to confuse it with the
603 &lsquo;height&rsquo; field in
604 the <a href="../reference/ft2-glyph_retrieval.html#ft_glyph_metrics"><code>FT_Glyph_Metrics</code></a>
605 structure.</p>
606 </dd>
607
608 <dt>max_advance</dt>
609 <dd>The scaled version of the original design maximum
610 advance, rounded to an integer value.</dd>
611 </dl>
612
613 <p>Note that the <code>face-&gt;size-&gt;metrics</code>
614 structure contains other fields that are used to scale
615 design coordinates to device space. They are described in
616 the last section.</p>
617
618 <h4>c. Kerning</h4>
619
620 <p>Kerning is the process of adjusting the position of two
621 subsequent glyph images in a string of text in order to
622 improve the general appearance of text. For example, if a
623 glyph for an uppercase &lsquo;A&rsquo; is followed by a
624 glyph for an uppercase &lsquo;V&rsquo;, the space between
625 the two glyphs can be slightly reduced to avoid extra
626 &lsquo;diagonal whitespace&rsquo;.</p>
627
628 <p>Note that in theory kerning can happen both in the
629 horizontal and vertical direction between two glyphs;
630 however, it only happens in a single direction in nearly
631 all cases.</p>
632
633 <p>Not all font formats contain kerning information, and not
634 all kerning formats are supported by FreeType; in
635 particular, for TrueType fonts, the API can only access
636 kerning via the &lsquo;kern&rsquo;
637 table. <span class="important">OpenType kerning via the
638 &lsquo;GPOS&rsquo; table is not supported!</span> You
639 need a higher-level library
640 like <a href="https://harfbuzz.github.io/">HarfBuzz</a>,
641 <a href="http://www.pango.org">Pango</a>,
642 or <a href="https://icu-project.org/">ICU</a>, since
643 GPOS kerning requires contextual string handling.</p>
644
645 <p>Sometimes, the font file is associated with an additional
646 file that contains various glyph metrics, including
647 kerning, but no glyph images. A good example is the
648 Type&nbsp;1 format where glyph images are stored in files
649 with extension <code>.pfa</code> or <code>.pfb</code>,
650 while kerning metrics can be found in files with extension
651 <code>.afm</code> or <code>.pfm</code>.</p>
652
653 <p>FreeType&nbsp;2 allows you to deal with this, by
654 providing
655 the <a href="../reference/ft2-face_creation.html#ft_attach_file"><code>FT_Attach_File</code></a>
656 and <a href="../reference/ft2-face_creation.html#ft_attach_stream"><code>FT_Attach_Stream</code></A>
657 APIs. Both functions are used to load additional metrics
658 into a face object by reading them from an additional
659 format-specific file. Here an example, opening a
660 Type&nbsp;1 font.</p>
661
662 <pre>
663 error = FT_New_Face( library, "/usr/share/fonts/cour.pfb",
664 0, &amp;face );
665 if ( error ) { ... }
666
667 error = FT_Attach_File( face, "/usr/share/fonts/cour.afm" );
668 if ( error )
669 { ... could not read kerning and additional metrics ... }</pre>
670
671 <p>Note that <code>FT_Attach_Stream</code> is similar to
672 <code>FT_Attach_File</code> except that it doesn't take a
673 C&nbsp;string to name the extra file but
674 an <a href="../reference/ft2-system_interface.html#ft_streamrec"><code>FT_Stream</code></a>
675 handle. Also, <em>reading a metrics file is in no way
676 mandatory</em>.</p>
677
678 <p>Finally, the file attachment APIs are very generic and
679 can be used to load any kind of extra information for a
680 given face. The nature of the additional content is
681 entirely font format specific.</p>
682
683 <p>FreeType&nbsp;2 allows you to retrieve the kerning
684 information between two glyphs through
685 the <a href="../reference/ft2-glyph_retrieval.html#ft_get_kerning"><code>FT_Get_Kerning</code></a>
686 function.</p>
687
688 <pre>
689 FT_Vector kerning;
690
691
692 ...
693 error = FT_Get_Kerning( face, <span class="comment">/* handle to face object */</span>
694 left, <span class="comment">/* left glyph index */</span>
695 right, <span class="comment">/* right glyph index */</span>
696 <em>kerning_mode</em>, <span class="comment">/* kerning mode */</span>
697 &amp;kerning ); <span class="comment">/* target vector */</span></pre>
698
699 <p>This function takes a handle to a face object, the
700 indices of the left and right glyph for which the kerning
701 value is desired, an integer, called the <em>kerning
702 mode</em>, and a pointer to a destination vector that
703 receives the corresponding distances.</p>
704
705 <p>The kerning mode is very similar to the <em>bbox
706 mode</em> described in a previous section. It is a
707 enumeration that indicates how the kerning distances are
708 expressed in the target vector.</p>
709
710 <p>The default value is <code>FT_KERNING_DEFAULT</code>,
711 which has value&nbsp;0. It corresponds to kerning
712 distances expressed in 26.6 grid-fitted pixels (which
713 means that the values are multiples of 64). For scalable
714 formats, this means that the design kerning distance is
715 scaled, then rounded.</p>
716
717 <p>The value <code>FT_KERNING_UNFITTED</code> corresponds to
718 kerning distances expressed in 26.6 unfitted pixels (i.e.,
719 that do not correspond to integer coordinates). It is the
720 design kerning distance that is scaled without
721 rounding.</p>
722
723 <p>Finally, the value <code>FT_KERNING_UNSCALED</code>
724 indicates to return the design kerning distance, expressed
725 in font units. You can later scale it to the device space
726 using the computations explained in the last section of
727 this part.</p>
728
729 <p>Note that the &lsquo;left&rsquo; and &lsquo;right&rsquo;
730 positions correspond to the <em>visual order</em> of the
731 glyphs in the string of text. This is important for
732 bidirectional or right-to-left text.</p>
733
734
735 <h3 id="section-4">4. Simple Text Rendering: Kerning and Centering</h3>
736
737 <p>In order to show off what we have just learned, we now
738 demonstrate how to modify
739 the <a href="step1.html#basic-code">example code</a> that
740 was provided in part&nbsp;I to render a string of text,
741 and enhance it to support kerning and delayed
742 rendering.</p>
743
744 <h4>a. Kerning Support</h4>
745
746 <p>Adding support for kerning to our code is trivial, as
747 long as we consider that we are still dealing with a
748 left-to-right script like Latin. We simply need to
749 retrieve the kerning distance between two glyphs in order
750 to alter the pen position appropriately.</p>
751
752 <pre>
753 FT_GlyphSlot slot = face-&gt;glyph; <span class="comment">/* a small shortcut */</span>
754 FT_UInt glyph_index;
755 FT_Bool use_kerning;
756 FT_UInt previous;
757 int pen_x, pen_y, n;
758
759
760 ... initialize library ...
761 ... create face object ...
762 ... set character size ...
763
764 pen_x = 300;
765 pen_y = 200;
766
767 use_kerning = FT_HAS_KERNING( face );
768 previous = 0;
769
770 for ( n = 0; n &lt; num_chars; n++ )
771 {
772 <span class="comment">/* convert character code to glyph index */</span>
773 glyph_index = FT_Get_Char_Index( face, text[n] );
774
775 <span class="comment">/* retrieve kerning distance and move pen position */</span>
776 if ( use_kerning &amp;&amp; previous &amp;&amp; glyph_index )
777 {
778 FT_Vector delta;
779
780
781 FT_Get_Kerning( face, previous, glyph_index,
782 FT_KERNING_DEFAULT, &amp;delta );
783
784 pen_x += delta.x &gt;&gt; 6;
785 }
786
787 <span class="comment">/* load glyph image into the slot (erase previous one) */</span>
788 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER );
789 if ( error )
790 continue; <span class="comment">/* ignore errors */</span>
791
792 <span class="comment">/* now draw to our target surface */</span>
793 my_draw_bitmap( &amp;slot-&gt;bitmap,
794 pen_x + slot-&gt;bitmap_left,
795 pen_y - slot-&gt;bitmap_top );
796
797 <span class="comment">/* increment pen position */</span>
798 pen_x += slot->advance.x &gt;&gt; 6;
799
800 <span class="comment">/* record current glyph index */</span>
801 previous = glyph_index;
802 }</pre>
803
804 <p>We are done. Some notes.</p>
805
806 <ul>
807 <li>As kerning is determined by glyph indices, we need to
808 explicitly convert our character codes into glyph
809 indices, then later call <code>FT_Load_Glyph</code>
810 instead of <code>FT_Load_Char</code>.</li>
811
812 <li>We use a boolean named <code>use_kerning</code>, which
813 is set to the result of the
814 macro <code>FT_HAS_KERNING</code>. It is certainly
815 faster not to call <code>FT_Get_Kerning</code> when we
816 know that the font face does not contain kerning
817 information.</li>
818
819 <li>We move the position of the pen <em>before</em> a new
820 glyph is drawn.</li>
821
822 <li>We initialize the variable <code>previous</code> with
823 the value&nbsp;0, which always corresponds to the
824 &lsquo;missing glyph&rsquo; (also
825 called <code>.notdef</code> in the PostScript world).
826 There is never any kerning distance associated with this
827 glyph.</li>
828
829 <li>We do not check the error code returned by
830 <code>FT_Get_Kerning</code>. This is because the
831 function always sets the content of <code>delta</code>
832 to (0,0) if an error occurs.</li>
833 </ul>
834
835 <h4>b. Centering</h4>
836
837 <p>Our code begins to become interesting but it is still a
838 bit too simple for normal use. For example, the position
839 of the pen is determined before we do the rendering;
840 normally, you would rather determine the layout of the
841 text and measure it before computing its final position
842 (centering, etc.), or perform things like
843 word-wrapping.</p>
844
845 <p>Let us now decompose our text rendering function into two
846 distinct but successive parts: The first one positions
847 individual glyph images on the baseline, while the second
848 one renders the glyphs. As we will see, this has many
849 advantages.</p>
850
851 <p>We thus start by storing individual glyph images, as well
852 as their position on the baseline.</p>
853
854 <pre>
855 FT_GlyphSlot slot = face-&gt;glyph; <span class="comment">/* a small shortcut */</span>
856 FT_UInt glyph_index;
857 FT_Bool use_kerning;
858 FT_UInt previous;
859 int pen_x, pen_y, n;
860
861 FT_Glyph glyphs[MAX_GLYPHS]; <span class="comment">/* glyph image */</span>
862 FT_Vector pos [MAX_GLYPHS]; <span class="comment">/* glyph position */</span>
863 FT_UInt num_glyphs;
864
865
866 ... initialize library ...
867 ... create face object ...
868 ... set character size ...
869
870 pen_x = 0; <span class="comment">/* start at (0,0) */</span>
871 pen_y = 0;
872
873 num_glyphs = 0;
874 use_kerning = FT_HAS_KERNING( face );
875 previous = 0;
876
877 for ( n = 0; n &lt; num_chars; n++ )
878 {
879 <span class="comment">/* convert character code to glyph index */</span>
880 glyph_index = FT_Get_Char_Index( face, text[n] );
881
882 <span class="comment">/* retrieve kerning distance and move pen position */</span>
883 if ( use_kerning &amp;&amp; previous &amp;&amp; glyph_index )
884 {
885 FT_Vector delta;
886
887
888 FT_Get_Kerning( face, previous, glyph_index,
889 FT_KERNING_DEFAULT, &amp;delta );
890
891 pen_x += delta.x &gt;&gt; 6;
892 }
893
894 <span class="comment">/* store current pen position */</span>
895 pos[num_glyphs].x = pen_x;
896 pos[num_glyphs].y = pen_y;
897
898 <span class="comment">/* load glyph image into the slot without rendering */</span>
899 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );
900 if ( error )
901 continue; <span class="comment">/* ignore errors, jump to next glyph */</span>
902
903 <span class="comment">/* extract glyph image and store it in our table */</span>
904 error = FT_Get_Glyph( face-&gt;glyph, &amp;glyphs[num_glyphs] );
905 if ( error )
906 continue; <span class="comment">/* ignore errors, jump to next glyph */</span>
907
908 <span class="comment">/* increment pen position */</span>
909 pen_x += slot->advance.x &gt;&gt; 6;
910
911 <span class="comment">/* record current glyph index */</span>
912 previous = glyph_index;
913
914 <span class="comment">/* increment number of glyphs */</span>
915 num_glyphs++;
916 }</pre>
917
918 <p>This is a very slight variation of our previous code; we
919 extract each glyph image from the slot, then store it,
920 along with the corresponding position, in our tables.</p>
921
922 <p>Note also that <code>pen_x</code> contains the total
923 advance for the string of text. We can now compute the
924 bounding box of the text string with a simple
925 function.</p>
926
927 <pre>
928 void compute_string_bbox( FT_BBox *abbox )
929 {
930 FT_BBox bbox;
931 FT_BBox glyph_bbox;
932
933
934 <span class="comment">/* initialize string bbox to "empty" values */</span>
935 bbox.xMin = bbox.yMin = 32000;
936 bbox.xMax = bbox.yMax = -32000;
937
938 <span class="comment">/* for each glyph image, compute its bounding box, */</span>
939 <span class="comment">/* translate it, and grow the string bbox */</span>
940 for ( n = 0; n &lt; num_glyphs; n++ )
941 {
942 FT_Glyph_Get_CBox( glyphs[n], ft_glyph_bbox_pixels,
943 &amp;glyph_bbox );
944
945 glyph_bbox.xMin += pos[n].x;
946 glyph_bbox.xMax += pos[n].x;
947 glyph_bbox.yMin += pos[n].y;
948 glyph_bbox.yMax += pos[n].y;
949
950 if ( glyph_bbox.xMin &lt; bbox.xMin )
951 bbox.xMin = glyph_bbox.xMin;
952
953 if ( glyph_bbox.yMin &lt; bbox.yMin )
954 bbox.yMin = glyph_bbox.yMin;
955
956 if ( glyph_bbox.xMax &gt; bbox.xMax )
957 bbox.xMax = glyph_bbox.xMax;
958
959 if ( glyph_bbox.yMax &gt; bbox.yMax )
960 bbox.yMax = glyph_bbox.yMax;
961 }
962
963 <span class="comment">/* check that we really grew the string bbox */</span>
964 if ( bbox.xMin &gt; bbox.xMax )
965 {
966 bbox.xMin = 0;
967 bbox.yMin = 0;
968 bbox.xMax = 0;
969 bbox.yMax = 0;
970 }
971
972 <span class="comment">/* return string bbox */</span>
973 *abbox = bbox;
974 }</pre>
975
976 <p>The resulting bounding box dimensions are expressed in
977 integer pixels and can then be used to compute the final
978 pen position before rendering the string.</p>
979
980 <p class="warning">In general, the above function
981 does <em>not</em> compute an exact bounding box of a
982 string! As soon as hinting is involved, glyph
983 dimensions <em>must</em> be derived from the resulting
984 outlines. For anti-aliased pixmaps,
985 <code>FT_Outline_Get_BBox</code> then yields proper
986 results. In case you need 1-bit monochrome bitmaps, it is
987 even necessary to actually render the glyphs because the
988 rules for the conversion from outline to bitmap can also
989 be controlled by hinting instructions
990 (cf. <a href="https://learn.microsoft.com/typography/opentype/spec/ttch01#the-scan-converter">dropout
991 control</a>).</p>
992
993 <pre>
994 <span class="comment">/* compute string dimensions in integer pixels */</span>
995 string_width = string_bbox.xMax - string_bbox.xMin;
996 string_height = string_bbox.yMax - string_bbox.yMin;
997
998 <span class="comment">/* compute start pen position in 26.6 Cartesian pixels */</span>
999 start_x = ( ( my_target_width - string_width ) / 2 ) * 64;
1000 start_y = ( ( my_target_height - string_height ) / 2 ) * 64;
1001
1002 for ( n = 0; n &lt; num_glyphs; n++ )
1003 {
1004 FT_Glyph image;
1005 FT_Vector pen;
1006
1007
1008 image = glyphs[n];
1009
1010 pen.x = start_x + pos[n].x;
1011 pen.y = start_y + pos[n].y;
1012
1013 error = FT_Glyph_To_Bitmap( &amp;image, FT_RENDER_MODE_NORMAL,
1014 &amp;pen, 0 );
1015 if ( !error )
1016 {
1017 FT_BitmapGlyph bit = (FT_BitmapGlyph)image;
1018
1019
1020 my_draw_bitmap( bit-&gt;bitmap,
1021 bit-&gt;left,
1022 my_target_height - bit-&gt;top );
1023
1024 FT_Done_Glyph( image );
1025 }
1026 }</pre>
1027
1028 <p>Some remarks.</p>
1029
1030 <ul>
1031 <li>The pen position is expressed in the Cartesian space
1032 (i.e., y&nbsp;upwards).</li>
1033
1034 <li>We call <code>FT_Glyph_To_Bitmap</code> with
1035 the <code>destroy</code> parameter set to&nbsp;0
1036 (false), in order to avoid destroying the original glyph
1037 image. The new glyph bitmap is accessed through
1038 <code>image</code> after the call and is typecast to
1039 <code>FT_BitmapGlyph</code>.</li>
1040
1041 <li>We use translation when
1042 calling <code>FT_Glyph_To_Bitmap</code>. This ensures
1043 that the <code>left</code> and <code>top</code> fields
1044 of the bitmap glyph object are already set to the
1045 correct pixel coordinates in the Cartesian space.</li>
1046
1047 <li>Of course, we still need to convert pixel coordinates
1048 from Cartesian to device space before rendering, hence
1049 the <code>my_target_height - bitmap->top</code> in the
1050 call to <code>my_draw_bitmap</code>.</li>
1051 </ul>
1052
1053 <p>The same loop can be used to render the string anywhere
1054 on our display surface, without the need to reload our
1055 glyph images each time.</p>
1056
1057
1058 <h3 id="section-5">5. Advanced Text Rendering:
1059 Transformation and Centering and Kerning</h3>
1060
1061 <p>We are now going to modify our code in order to be able
1062 to easily transform the rendered string, for example, to
1063 rotate it. First, some minor improvements.</p>
1064
1065 <h4>a. Packing and Translating Glyphs</h4>
1066
1067 <p>We start by packing the information related to a single
1068 glyph image into a single structure instead of parallel
1069 arrays.</p>
1070
1071 <pre>
1072 typedef struct TGlyph_
1073 {
1074 FT_UInt index; <span class="comment">/* glyph index */</span>
1075 FT_Vector pos; <span class="comment">/* glyph origin on the baseline */</span>
1076 FT_Glyph image; <span class="comment">/* glyph image */</span>
1077
1078 } TGlyph, *PGlyph;</pre>
1079
1080 <p>We also translate each glyph image directly after it is
1081 loaded to its position on the baseline at load time. As
1082 we will see, this has several advantages. Here is our new
1083 glyph sequence loader.</p>
1084
1085 <pre>
1086 FT_GlyphSlot slot = face-&gt;glyph; <span class="comment">/* a small shortcut */</span>
1087 FT_UInt glyph_index;
1088 FT_Bool use_kerning;
1089 FT_UInt previous;
1090 int pen_x, pen_y, n;
1091
1092 TGlyph glyphs[MAX_GLYPHS]; <span class="comment">/* glyphs table */</span>
1093 PGlyph glyph; <span class="comment">/* current glyph in table */</span>
1094 FT_UInt num_glyphs;
1095
1096
1097 ... initialize library ...
1098 ... create face object ...
1099 ... set character size ...
1100
1101 pen_x = 0; <span class="comment">/* start at (0,0) */</span>
1102 pen_y = 0;
1103
1104 num_glyphs = 0;
1105 use_kerning = FT_HAS_KERNING( face );
1106 previous = 0;
1107
1108 glyph = glyphs;
1109 for ( n = 0; n &lt; num_chars; n++ )
1110 {
1111 glyph-&gt;index = FT_Get_Char_Index( face, text[n] );
1112
1113 if ( use_kerning &amp;&amp; previous &amp;&amp; glyph->index )
1114 {
1115 FT_Vector delta;
1116
1117
1118 FT_Get_Kerning( face, previous, glyph-&gt;index,
1119 FT_KERNING_MODE_DEFAULT, &amp;delta );
1120
1121 pen_x += delta.x &gt;&gt; 6;
1122 }
1123
1124 <span class="comment">/* store current pen position */</span>
1125 glyph->pos.x = pen_x;
1126 glyph->pos.y = pen_y;
1127
1128 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );
1129 if ( error ) continue;
1130
1131 error = FT_Get_Glyph( face-&gt;glyph, &amp;glyph-&gt;image );
1132 if ( error ) continue;
1133
1134 <span class="comment">/* translate the glyph image now */</span>
1135 FT_Glyph_Transform( glyph-&gt;image, 0, &amp;glyph-&gt;pos );
1136
1137 pen_x += slot->advance.x &gt;&gt; 6;
1138 previous = glyph->index;
1139
1140 <span class="comment">/* increment number of glyphs */</span>
1141 glyph++;
1142 }
1143
1144 <span class="comment">/* count number of glyphs loaded */</span>
1145 num_glyphs = glyph - glyphs;</pre>
1146
1147 <p>Note that translating glyphs now has several advantages.
1148 The first one is that we don't need to translate the glyph
1149 bbox when we compute the string's bounding box.</p>
1150
1151 <pre>
1152 void compute_string_bbox( FT_BBox *abbox )
1153 {
1154 FT_BBox bbox;
1155
1156
1157 bbox.xMin = bbox.yMin = 32000;
1158 bbox.xMax = bbox.yMax = -32000;
1159
1160 for ( n = 0; n &lt; num_glyphs; n++ )
1161 {
1162 FT_BBox glyph_bbox;
1163
1164
1165 FT_Glyph_Get_CBox( glyphs[n], ft_glyph_bbox_pixels,
1166 &amp;glyph_bbox );
1167
1168 if (glyph_bbox.xMin &lt; bbox.xMin)
1169 bbox.xMin = glyph_bbox.xMin;
1170
1171 if (glyph_bbox.yMin &lt; bbox.yMin)
1172 bbox.yMin = glyph_bbox.yMin;
1173
1174 if (glyph_bbox.xMax &gt; bbox.xMax)
1175 bbox.xMax = glyph_bbox.xMax;
1176
1177 if (glyph_bbox.yMax &gt; bbox.yMax)
1178 bbox.yMax = glyph_bbox.yMax;
1179 }
1180
1181 if ( bbox.xMin > bbox.xMax )
1182 {
1183 bbox.xMin = 0;
1184 bbox.yMin = 0;
1185 bbox.xMax = 0;
1186 bbox.yMax = 0;
1187 }
1188
1189 *abbox = bbox;
1190 }</pre>
1191
1192 <p>With the above modifications,
1193 the <code>compute_string_bbox</code> function can now
1194 compute the bounding box of a transformed glyph string,
1195 which allows further code simplications.</p>
1196
1197 <pre>
1198 FT_BBox bbox;
1199 FT_Matrix matrix;
1200 FT_Vector delta;
1201
1202
1203 ... load glyph sequence ...
1204 ... set up `matrix' and `delta' ...
1205
1206 <span class="comment">/* transform glyphs */</span>
1207 for ( n = 0; n &lt; num_glyphs; n++ )
1208 FT_Glyph_Transform( glyphs[n].image, &amp;matrix, &amp;delta );
1209
1210 <span class="comment">/* compute bounding box of transformed glyphs */</span>
1211 compute_string_bbox( &amp;bbox );</pre>
1212
1213 <h4>b. Rendering a Transformed Glyph Sequence</h4>
1214
1215 <p>However, directly transforming the glyphs in our sequence
1216 is not a good idea if we want to reuse them in order to
1217 draw the text string with various angles or
1218 transformations. It is better to perform the affine
1219 transformation just before the glyph is rendered.</p>
1220
1221 <pre>
1222 FT_Vector start;
1223 FT_Matrix matrix;
1224
1225 FT_Glyph image;
1226 FT_Vector pen;
1227 FT_BBox bbox;
1228
1229
1230 <span class="comment">/* get bbox of original glyph sequence */</span>
1231 compute_string_bbox( &amp;string_bbox );
1232
1233 <span class="comment">/* compute string dimensions in integer pixels */</span>
1234 string_width = (string_bbox.xMax - string_bbox.xMin) / 64;
1235 string_height = (string_bbox.yMax - string_bbox.yMin) / 64;
1236
1237 <span class="comment">/* set up start position in 26.6 Cartesian space */</span>
1238 start.x = ( ( my_target_width - string_width ) / 2 ) * 64;
1239 start.y = ( ( my_target_height - string_height ) / 2 ) * 64;
1240
1241 <span class="comment">/* set up transform (a rotation here) */</span>
1242 matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L );
1243 matrix.xy = (FT_Fixed)(-sin( angle ) * 0x10000L );
1244 matrix.yx = (FT_Fixed)( sin( angle ) * 0x10000L );
1245 matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L );
1246
1247 pen = start;
1248
1249 for ( n = 0; n &lt; num_glyphs; n++ )
1250 {
1251 <span class="comment">/* create a copy of the original glyph */</span>
1252 error = FT_Glyph_Copy( glyphs[n].image, &amp;image );
1253 if ( error ) continue;
1254
1255 <span class="comment">/* transform copy (this will also translate it to the */</span>
1256 <span class="comment">/* correct position */</span>
1257 FT_Glyph_Transform( image, &amp;matrix, &amp;pen );
1258
1259 <span class="comment">/* check bounding box; if the transformed glyph image */</span>
1260 <span class="comment">/* is not in our target surface, we can avoid rendering it */</span>
1261 FT_Glyph_Get_CBox( image, ft_glyph_bbox_pixels, &amp;bbox );
1262 if ( bbox.xMax &lt;= 0 || bbox.xMin &gt;= my_target_width ||
1263 bbox.yMax &lt;= 0 || bbox.yMin &gt;= my_target_height )
1264 continue;
1265
1266 <span class="comment">/* convert glyph image to bitmap (destroy the glyph copy!) */</span>
1267 error = FT_Glyph_To_Bitmap(
1268 &amp;image,
1269 FT_RENDER_MODE_NORMAL,
1270 0, <span class="comment">/* no additional translation */</span>
1271 1 ); <span class="comment">/* destroy copy in "image" */</span>
1272 if ( !error )
1273 {
1274 FT_BitmapGlyph bit = (FT_BitmapGlyph)image;
1275
1276
1277 my_draw_bitmap( bit-&gt;bitmap,
1278 bit-&gt;left,
1279 my_target_height - bit-&gt;top );
1280
1281 <span class="comment">/* increment pen position -- */</span>
1282 <span class="comment">/* we don't have access to a slot structure, */</span>
1283 <span class="comment">/* so we have to use advances from glyph structure */</span>
1284 <span class="comment">/* (which are in 16.16 fixed float format) */</span>
1285 pen.x += image.advance.x >> 10;
1286 pen.y += image.advance.y >> 10;
1287
1288 FT_Done_Glyph( image );
1289 }
1290 }</pre>
1291
1292 <p>There are a few changes compared to the original version
1293 of this code.</p>
1294
1295 <ul>
1296 <li>We keep the original glyph images untouched; instead,
1297 we transform a copy.</li>
1298
1299 <li>We perform clipping computations in order to avoid
1300 rendering and drawing glyphs that are not within our
1301 target surface.</li>
1302
1303 <li>We always destroy the copy when calling
1304 <code>FT_Glyph_To_Bitmap</code> in order to get rid of
1305 the transformed scalable image. Note that the image is
1306 not destroyed if the function returns an error code
1307 (which is why <code>FT_Done_Glyph</code> is only called
1308 within the compound statement).</li>
1309
1310 <li>The translation of the glyph sequence to the start pen
1311 position is integrated into the call
1312 to <code>FT_Glyph_Transform</code> instead
1313 of <code>FT_Glyph_To_Bitmap</code>.</li>
1314 </ul>
1315
1316 <p>It is possible to call this function several times to
1317 render the string with different angles, or even change
1318 the way <code>start</code> is computed in order to move it
1319 to different place.</p>
1320
1321 <p>This code is the basis of the FreeType&nbsp;2
1322 demonstration program
1323 named <a href="https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/ftstring.c"><code>ftstring.c</code></a>.
1324 It could be easily extended to perform advanced text
1325 layout or word-wrapping in the first part, without
1326 changing the second one.</p>
1327
1328 <p>Note, however, that a normal implementation would use a
1329 glyph cache in order to reduce memory needs. For example,
1330 let us assume that our text string is
1331 &lsquo;FreeType&rsquo;. We would store three identical
1332 glyph images in our table for the letter &lsquo;e&rsquo;,
1333 which isn't optimal (especially when you consider longer
1334 lines of text, or even whole pages).</p>
1335
1336 <p>A FreeType demo program that shows how glyph caching can
1337 be implemented
1338 is <a href="https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/ftview.c"><code>ftview.c</code></a>.
1339 In general, &lsquo;ftview&rsquo; is the main program used
1340 by the FreeType developer team to check the validity of
1341 loading, parsing, and rendering fonts.</p>
1342
1343 <p>Another very useful demo program
1344 is <a href="https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/ftstring.c"><code>ftdiff.c</code></a>,
1345 demonstrating the use and the optical results of the
1346 various rendering and hinting modes provided by FreeType.
1347 In particular, it also demonstrates how to do sub-pixel
1348 positioning (for unhinted glyphs and &lsquo;light&rsquo;
1349 hinting mode) &ndash; all code in this tutorial assumes
1350 integer coordinates.</p>
1351
1352
1353 <h3 id="section-6">6. Accessing Metrics in Design Font
1354 Units, and Scaling Them</h3>
1355
1356 <p>Scalable font formats usually store a single vectorial
1357 image, called an <em>outline</em>, for each glyph in a
1358 face. Each outline is defined in an abstract grid called
1359 the <em>design space</em>, with coordinates expressed in
1360 <em>font units</em>. When a glyph image is loaded, the
1361 font driver usually scales the outline to device space
1362 according to the current character pixel size found in
1363 an <a href="../reference/ft2-sizing_and_scaling.html#ft_size"><code>FT_Size</code></a>
1364 object. The driver may also modify the scaled outline in
1365 order to significantly improve its appearance on a
1366 pixel-based surface (a process known as <em>hinting</em>
1367 or <em>grid-fitting</em>).</p>
1368
1369 <p>This section describes how design coordinates are scaled
1370 to the device space, and how to read glyph outlines and
1371 metrics in font units. This is important for a number of
1372 things.</p>
1373
1374 <ul>
1375 <li>&lsquo;True&rsquo; WYSIWYG text layout.</li>
1376 <li>Accessing font content for conversion or analysis
1377 purposes.</li>
1378 </ul>
1379
1380 <h4>a. Scaling Distances to Device Space</h4>
1381
1382 <p>Design coordinates are scaled to the device space using a
1383 simple scaling transformation whose coefficients are
1384 computed with the help of the <em>character pixel
1385 size</em>.</p>
1386
1387 <pre class="example">
1388 device_x = design_x * x_scale
1389 device_y = design_y * y_scale
1390
1391 x_scale = pixel_size_x / EM_size
1392 y_scale = pixel_size_y / EM_size</pre>
1393
1394 <p>Here, the value <code>EM_size</code> is font-specific and
1395 corresponds to the size of an abstract square of the
1396 design space (called the <em>EM</em>), which is used by
1397 font designers to create glyph images. It is thus
1398 expressed in font units. It is also accessible directly
1399 for scalable font formats
1400 as <code>face-&gt;units_per_EM</code>. You should check
1401 that a font face contains scalable glyph images by using
1402 the <code>FT_IS_SCALABLE</code> macro, which returns true
1403 if appropriate.</p>
1404
1405 <p>When you call the
1406 function <a href="../reference/ft2-sizing_and_scaling.html#ft_set_pixel_sizes"><code>FT_Set_Pixel_Sizes</code></a>,
1407 you are specifying integer values
1408 of <code>pixel_size_x</code> and
1409 <code>pixel_size_y</code> FreeType shall use. The library
1410 will immediately compute the values
1411 of <code>x_scale</code> and
1412 <code>y_scale</code>.</p>
1413
1414 <p>When you call the
1415 function <a href="../reference/ft2-sizing_and_scaling.html#ft_set_char_size"><code>FT_Set_Char_Size</code></a>,
1416 you are specifying the character size in
1417 physical <em>points</em>, which is used, along with the
1418 device's resolutions, to compute the character pixel size
1419 and the corresponding scaling factors. Here, the scaling
1420 factors can correspond to fractional ppem values.</p>
1421
1422 <p>Note that after calling any of these two functions, you
1423 can access the values of the character pixel size and
1424 scaling factors as fields of
1425 the <code>face-&gt;size-&gt;metrics</code> structure.</p>
1426
1427 <dl>
1428 <dt>x_ppem</dt>
1429 <dd>The field name stands for &lsquo;x&nbsp;pixels per
1430 EM&rsquo;; this is the horizontal size rounded to
1431 integer pixels of the EM square, which also is
1432 the <em>horizontal character pixel size</em>,
1433 called <code>pixel_size_x</code> in the above
1434 example.</dd>
1435
1436 <dt>y_ppem</dt>
1437 <dd>The field name stands for &lsquo;y&nbsp;pixels per
1438 EM&rsquo;; this is the vertical size rounded to integer
1439 pixels of the EM square, which also is the <em>vertical
1440 character pixel size</em>,
1441 called <code>pixel_size_y</code> in the above
1442 example.</dd>
1443
1444 <dt>x_scale</dt>
1445 <dd>This is a 16.16 fixed-point scale to directly scale
1446 horizontal distances from design space to 1/64 of device
1447 pixels.</dd>
1448
1449 <dt>y_scale</dt>
1450 <dd>This is a 16.16 fixed-point scale to directly scale
1451 vertical distances from design space to 1/64 of device
1452 pixels.</dd>
1453 </dl>
1454
1455 <p>You can scale a distance expressed in font units to 26.6
1456 pixel format directly with the help of
1457 the <a href="../reference/ft2-computations.html#ft_mulfix"><code>FT_MulFix</code></a>
1458 function.</p>
1459
1460 <pre>
1461 <span class="comment">/* convert design distances to 1/64 of pixels */</span>
1462 pixels_x = FT_MulFix( design_x, face-&gt;size-&gt;metrics.x_scale );
1463 pixels_y = FT_MulFix( design_y, face-&gt;size-&gt;metrics.y_scale );</pre>
1464
1465 <p>Alternatively, you can also scale the value directly by
1466 using doubles.</p>
1467
1468 <pre>
1469 FT_Size_Metrics* metrics = &amp;face-&gt;size-&gt;metrics; <span class="comment">/* shortcut */</span>
1470 double pixels_x, pixels_y;
1471 double x_scale, y_scale;
1472
1473
1474 <span class="comment">/* compute floating point scale factors */</span>
1475 x_scale = face-&gt;size-&gt;metrics.x_scale / 65536.0;
1476 y_scale = face-&gt;size-&gt;metrics.y_scale / 65536.0;
1477
1478 <span class="comment">/* convert design distances to floating point pixels */</span>
1479 pixels_x = design_x * x_scale;
1480 pixels_y = design_y * y_scale;</pre>
1481
1482 <h4>b. Accessing Design Metrics (Glyph &amp; Global)</h4>
1483
1484 <p>You can access glyph metrics in font units simply by
1485 specifying the <code>FT_LOAD_NO_SCALE</code> bit flag
1486 in <code>FT_Load_Glyph</code>
1487 or <code>FT_Load_Char</code>. The metrics returned
1488 in <code>face-&gt;glyph-&gt;metrics</code> will all be in
1489 font units.</p>
1490
1491 <p>You can access unscaled kerning data using the
1492 <code>FT_KERNING_MODE_UNSCALED</code> mode.</p>
1493
1494 <p>Finally, a few global metrics are available directly in
1495 font units as fields of the <code>FT_Face</code> handle,
1496 as described in <a href="#section-3">section&nbsp;3</a> of
1497 this part.</p>
1498
1499
1500 <h3 id="conclusion">Conclusion</h3>
1501
1502 <p>This is the end of the second part of the FreeType
1503 tutorial. You are now able to access glyph metrics,
1504 manage glyph images, and render text much more
1505 intelligently (kerning, measuring, transforming &amp;
1506 caching); this is sufficient knowledge to build a pretty
1507 decent text service on top of FreeType.</p>
1508
1509 <p>The demo programs in the &lsquo;ft2demos&rsquo; bundle
1510 (especially &lsquo;ftview&rsquo;) are a kind of reference
1511 implementation, and are a good resource to turn to for
1512 answers. They also show how to use additional features,
1513 such as the glyph stroker and cache.</p>
1514 </div>
1515
1516 <!-- ************************************************** -->
1517
1518 <div class="updated">
1519 <p>Last update: 24-Oct-2022</p>
1520 </div>
1521 </div>
1522 </div>
1523
1524
1525 <!-- ************************************************** -->
1526
1527 <div class="col2">
1528 </div>
1529 </div>
1530 </div>
1531
1532
1533 <!-- ************************************************** -->
1534
1535 <div id="TOC">
1536 <ul>
1537 <li class="funding">
1538 <form action="https://www.paypal.com/cgi-bin/webscr"
1539 method="post"
1540 target="_top">
1541 <input type="hidden"
1542 name="cmd"
1543 value="_s-xclick">
1544 <input type="hidden"
1545 name="hosted_button_id"
1546 value="SK827YKEALMT4">
•1547 <input type="submit"
1548 value="Donate"
1549 name="submit"
1550 alt="PayPal - The safer, easier way to pay online!">
1551 </form>
1552 </li>
1553 <li class="primary">
1554 <a href="http://freetype.org/index.html">Home</a>
1555 </li>
1556 <li class="primary">
1557 <a href="http://freetype.org/index.html#news">News</a>
1558 </li>
1559 <li class="primary">
1560 <a href="../index.html">Overview</a>
1561 </li>
1562 <li class="primary">
1563 <a href="../documentation.html">Documentation</a>
1564 </li>
1565 <li class="primary">
1566 <a href="http://freetype.org/developer.html">Development</a>
1567 </li>
1568 <li class="primary">
1569 <a href="http://freetype.org/contact.html"
1570 class="emphasis">Contact</a>
1571 </li>
1572
1573 <li>
1574 &nbsp; <!-- separate primary from secondary entries -->
1575 </li>
1576
1577 <li class="secondary">
1578 <a href="index.html">FreeType Tutorial</a>
1579 </li>
1580 <li class="tertiary">
1581 <a href="step1.html">Simple Glyph Loading</a>
1582 </li>
1583 <li class="tertiary">
1584 <a href="step2.html" class="current">Managing Glyphs</a>
1585 </li>
1586 <li class="tertiary">
1587 <a href="step3.html">Examples</a>
1588 </li>
1589 </ul>
1590 </div>
1591
1592 </div> <!-- id="wrapper" -->
1593
1594 <div id="TOC-bottom">
1595 </div>
1596
1597 </body>
1598 </html>