File: step2.html

package info (click to toggle)
freetype 2.10.4%2Bdfsg-1%2Bdeb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 25,472 kB
  • sloc: ansic: 147,313; javascript: 7,011; python: 5,748; sh: 3,871; cpp: 3,706; xml: 1,338; makefile: 607; perl: 340; awk: 142; sed: 3
file content (1610 lines) | stat: -rw-r--r-- 64,310 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          "http://www.w3.org/TR/html4/loose.dtd">

<html lang="en">

<head>
  <meta http-equiv="Content-Type"
        content="text/html; charset=utf-8">
  <meta http-equiv="Content-Style-Type"
        content="text/css">
  <meta http-equiv="Content-Script-Type"
        content="text/javascript">
  <meta name="description"
        content="FreeType Documentation">
  <meta name="Author"
        content="David Turner">

  <link rel="icon"
        href="../image/favicon_-90.ico">
  <link rel="shortcut icon"
        href="../image/favicon_-90.ico">
  <link rel="stylesheet"
        type="text/css"
        href="../css/freetype2_-90.css">

  <script type="text/javascript"
          src="../js/jquery-1.11.0.min.js">
  </script>
  <script type="text/javascript"
          src="../js/jquery.ba-resize.min.js">
  </script>
  <script type="text/javascript"
          src="../js/freetype2.js">
  </script>

  <title>FreeType Tutorial / II</title>
</head>


<body>

<div id="top"
     class="bar">
  <h1><a href="http://freetype.org/index.html">FreeType</a>
    Tutorial&nbsp;/&nbsp;II</h1>
</div>


<div id="wrapper">

<div class="colmask leftmenu">
  <div class="colright">
    <div class="col1wrap">
      <div class="col1">


        <!-- ************************************************** -->

        <div id="simple-glyph-loading">
          <h2>II. Managing Glyphs</h2>


          <h3 id="section-1">1. Glyph Metrics</h3>

          <p>Glyph metrics are, as the name suggests, certain
            distances associated with each glyph that describe how to
            position this glyph while creating a text layout.</p>

          <p>There are usually two sets of metrics for a single glyph:
            Those used to represent glyphs in horizontal text layouts
            (Latin, Cyrillic, Arabic, Hebrew, etc.), and those used to
            represent glyphs in vertical text layouts (Chinese,
            Japanese, Korean, Mongolian, etc.).</p>

          <p>Note that only a few font formats provide vertical
            metrics.  You can test whether a given face object
            contains them by using the
            macro <a href="../reference/ft2-base_interface.html#ft_has_vertical"><code>FT_HAS_VERTICAL</code></a>,
            which returns true if appropriate.</p>

          <p>Individual glyph metrics can be accessed by first loading
            the glyph in a face's glyph slot, then accessing them
            through the <code>face-&gt;glyph-&gt;metrics</code>
            structure, whose type
            is <a href="../reference/ft2-base_interface.html#ft_glyph_metrics"><code>FT_Glyph_Metrics</code></a>.
            We will discuss this in more detail below; for now, we
            only note that it contains the following fields.</p>

          <dl>
            <dt>width</dt>
            <dd>This is the width of the glyph image's bounding box.
              It is independent of the layout direction.</dd>

            <dt>height</dt>
            <dd>This is the height of the glyph image's bounding box.
              It is independent of the layout direction.  Be careful
              not to confuse it with the &lsquo;height&rsquo; field in
              the <a href="../reference/ft2-base_interface.html#ft_size_metrics">
                <code>FT_Size_Metrics</code></a> structure.</dd>

            <dt>horiBearingX</dt>
            <dd>For <em>horizontal text layouts</em>, this is the
              horizontal distance from the current cursor position to
              the leftmost border of the glyph image's bounding
              box.</dd>

            <dt>horiBearingY</dt>
            <dd>For <em>horizontal text layouts</em>, this is the
              vertical distance from the current cursor position (on
              the baseline) to the topmost border of the glyph image's
              bounding box.</dd>

            <dt>horiAdvance</dt>
            <dd>For <em>horizontal text layouts</em>, this is the
              horizontal distance to increment the pen position when
              the glyph is drawn as part of a string of text.</dd>

            <dt>vertBearingX</dt>
            <dd>For <em>vertical text layouts</em>, this is the
              horizontal distance from the current cursor position to
              the leftmost border of the glyph image's bounding
              box.</dd>

            <dt>vertBearingY</dt>
            <dd>For <em>vertical text layouts</em>, this is the
              vertical distance from the current cursor position (on
              the baseline) to the topmost border of the glyph image's
              bounding box.</dd>

            <dt>vertAdvance</dt>
            <dd>For <em>vertical text layouts</em>, this is the
              vertical distance used to increment the pen position
              when the glyph is drawn as part of a string of
              text.</dd>
          </dl>

          <p class="warning">As not all fonts do contain vertical
            metrics, the values of <code>vertBearingX</code>,
            <code>vertBearingY</code> and <code>vertAdvance</code>
            should not be considered reliable
            if <code>FT_HAS_VERTICAL</code> returns false.</p>

          <p>The following graphics illustrate the metrics more
            clearly.  In case a distance is directed, it is marked
            with a single arrow, indicating a positive value.  The
            first image displays horizontal metrics, where the
            baseline is the horizontal axis.</p>

          <div class="figure">
            <img src="metrics.png"
                 alt="horizontal layout"
                 width=388
                 height=253>
          </div>

          <p>For vertical text layouts, the baseline is vertical,
            identical to the vertical axis.  Contrary to all other
            arrows, <code>bearingX</code> shows a negative value in
            this image.</p>

          <div class="figure">
            <img src="metrics2.png"
                 alt="vertical layout"
                 width=294
                 height=278>
          </div>

          <p>The metrics found
            in <code>face-&gt;glyph-&gt;metrics</code> are normally
            expressed in 26.6 pixel format (i.e., 1/64th of pixels),
            unless you use the <code>FT_LOAD_NO_SCALE</code> flag when
            calling <code>FT_Load_Glyph</code>
            or <code>FT_Load_Char</code>.  In this case, the metrics
            are expressed in original font units.</p>

          <p>The glyph slot object has also a few other interesting
            fields that eases a developer's work.  You can access them
            through <code>face-&gt;glyph-&gt;xxx</code>,
            where <code>xxx</code> is one of the following fields.</p>

          <dl>
            <dt>advance</dt>
            <dd>This field is a <code>FT_Vector</code> that holds the
              transformed advance for the glyph.  That is useful when
              you are using a transformation
              through <code>FT_Set_Transform</code>, as shown in the
              <a href="step1.html#transformed-text">rotated text
              example</a> of part&nbsp;I.  Other than that, its value
              is by default (metrics.horiAdvance,0), unless you
              specify <code>FT_LOAD_VERTICAL</code> when loading the
              glyph image; it is then (0,metrics.vertAdvance).</dd>

            <dt>linearHoriAdvance</dt>
            <dd>This field contains the linearly scaled value of the
              glyph's horizontal advance width.  Indeed, the value of
              <code>metrics.horiAdvance</code> that is returned in the
              glyph slot is normally rounded to integer pixel
              coordinates (i.e., being a multiple of&nbsp;64) by the
              font driver that actually loads the glyph
              image.  <code>linearHoriAdvance</code> is a 16.16
              fixed-point number that gives the value of the original
              glyph advance width in 1/65536th of pixels.  It can be
              use to perform pseudo device-independent text
              layouts.</dd>

            <dt>linearVertAdvance</dt>
            <dd>This is the similar to <code>linearHoriAdvance</code>
              but for the glyph's vertical advance height.  Its value
              is only reliable if the font face contains vertical
              metrics.</dd>
          </dl>


          <h3 id="section-2">2. Managing Glyph Images</h3>

          <p>The glyph image that is loaded in a glyph slot can be
            converted into a bitmap, either by
            using <code>FT_LOAD_RENDER</code> when loading it, or by
            calling <a href="../reference/ft2-base_interface.html#ft_render_glyph"><code>FT_Render_Glyph</code></a>.
            Each time you load a new glyph image, the previous one is
            erased from the glyph slot.</p>

          <p>There are situations, however, where you may need to
            extract this image from the glyph slot in order to cache
            it within your application, and even perform additional
            transformations and measures on it before converting it to
            a bitmap.</p>

          <p>The FreeType&nbsp;2 API has a specific extension that is
            capable of dealing with glyph images in a flexible and
            generic way.  To use it, you first need to include
            the <a href="../reference/ft2-header_file_macros.html#ft_glyph_h"><code>FT_GLYPH_H</code></a>
            header file.</p>

          <pre>
#include FT_GLYPH_H</pre>

          <h4>a.Extracting the Glyph Image</h4>

          <p>You can extract a single glyph image very easily.  Here
            some code that shows how to do it.</p>

          <pre>
FT_Glyph  glyph; <span class="comment">/* a handle to the glyph image */</span>


...
error = FT_Load_Glyph( face, glyph_index, FT_LOAD_NORMAL );
if ( error ) { ... }

error = FT_Get_Glyph( face-&gt;glyph, &amp;glyph );
if ( error ) { ... }</pre>

          <p>The following steps are performed.</p>

          <ul>
            <li>Create a variable named <code>glyph</code>, of
              type <a href="../reference/ft2-glyph_management.html#ft_glyph"><code>FT_Glyph</code></a>.
              This is a handle (pointer) to an individual glyph
              image.</li>

            <li>Load the glyph image in the normal way into the face's
              glyph slot.  We don't use <code>FT_LOAD_RENDER</code>
              because we want to grab a scalable glyph image that we
              can transform later on.</li>

            <li>Copy the glyph image from the slot into a
              new <code>FT_Glyph</code> object by
              calling <a href="../reference/ft2-glyph_management.html#ft_get_glyph"><code>FT_Get_Glyph</code></a>.
              This function returns an error code and
              sets <code>glyph</code>.</li>
          </ul>

          <p>It is important to note that the extracted glyph is in
            the same format as the original one that is still in the
            slot.  For example, if we are loading a glyph from a
            TrueType font file, the glyph image is really a scalable
            vector outline.  You can access the
            field <code>glyph-&gt;format</code> if you want to know
            exactly how the glyph is modeled and stored.</p>

          <p>A new glyph object can be destroyed with a call
            to <a href="../reference/ft2-glyph_management.html#ft_done_glyph"><code>FT_Done_Glyph</code></a>.</p>

          <p>The glyph object contains exactly one glyph image and a
            2D vector representing the glyph's advance in 16.16
            fixed-point coordinates.  The latter can be accessed
            directly as <code>glyph-&gt;advance</code></p>

          <p class="warning">Note that unlike other FreeType objects,
            the library doesn't keep a list of all allocated glyph
            objects.  This means you have to destroy them yourself
            instead of relying on <code>FT_Done_FreeType</code> doing
            all the clean-up.</p>

          <h4>b. Transforming &amp; Copying the Glyph Image</h4>

          <p>If the glyph image is scalable (i.e.,
            if <code>glyph-&gt;format</code> is not equal
            to <code>FT_GLYPH_FORMAT_BITMAP</code>), it is possible to
            transform the image anytime by a call
            to <a href="../reference/ft2-glyph_management.html#ft_glyph_transform"><code>FT_Glyph_Transform</code></a>.</p>

          <p>You can also copy a single glyph image
            with <a href="../reference/ft2-glyph_management.html#ft_glyph_copy"><code>FT_Glyph_Copy</code></a>.</p>

          <pre>
FT_Glyph   glyph, glyph2;
FT_Matrix  matrix;
FT_Vector  delta;


... load glyph image in `glyph' ...

<span class="comment">/* copy glyph to glyph2 */</span>

error = FT_Glyph_Copy( glyph, &amp;glyph2 );
if ( error ) { ... could not copy (out of memory) ... }

<span class="comment">/* translate `glyph' */</span>

delta.x = -100 * 64; <span class="comment">/* coordinates are in 26.6 pixel format */</span>
delta.y =   50 * 64;

FT_Glyph_Transform( glyph, 0, &amp;delta );

<span class="comment">/* transform glyph2 (horizontal shear) */</span>

matrix.xx = 0x10000L;
matrix.xy = 0.12 * 0x10000L;
matrix.yx = 0;
matrix.yy = 0x10000L;

FT_Glyph_Transform( glyph2, &amp;matrix, 0 );</pre>

          <p>Note that the 2&times;2 transformation matrix is always
            applied to the 16.16 advance vector in the glyph; you thus
            don't need to recompute it.</p>

          <h4>c. Measuring the Glyph Image</h4>

          <p>You can also retrieve the control (bounding) box of any
            glyph image (scalable or not) through
            the <a href="../reference/ft2-glyph_management.html#ft_glyph_get_cbox"><code>FT_Glyph_Get_CBox</code></a>
            function.</p>

          <pre>
FT_BBox  bbox;


...
FT_Glyph_Get_CBox( glyph, <em>bbox_mode</em>, &amp;bbox );</pre>

          <p>Coordinates are relative to the glyph origin (0,0), using
            the y&nbsp;upwards convention.  This function takes a
            special argument, the <em>bbox mode</em>, to indicate how
            box coordinates are expressed.</p>

          <p>If the glyph has been loaded
            with <code>FT_LOAD_NO_SCALE</code>, <code>bbox_mode</code>
            must be set to <code>FT_GLYPH_BBOX_UNSCALED</code> to get
            unscaled font units in 26.6 pixel format.  The
            value <code>FT_GLYPH_BBOX_SUBPIXELS</code> is another name
            for this constant.</p>

          <p>Note that the box's maximum coordinates are exclusive,
            which means that you can always compute the width and
            height of the glyph image (regardless of using integer or
            26.6 coordinates) with a simple subtraction.</p>

          <pre class="example">
width  = bbox.xMax - bbox.xMin;
height = bbox.yMax - bbox.yMin;</pre>

          <p>Note also that for 26.6 coordinates, if
            <code>FT_GLYPH_BBOX_GRIDFIT</code> is used as the bbox
            mode, the coordinates are also grid-fitted, which
            corresponds to the following four lines of
            pseudo-code.</p>

          <pre class="example">
bbox.xMin = FLOOR( bbox.xMin )
bbox.yMin = FLOOR( bbox.yMin )
bbox.xMax = CEILING( bbox.xMax )
bbox.yMax = CEILING( bbox.yMax )</pre>

          <p>To get the bbox in <em>integer</em> pixel coordinates,
            set <code>bbox_mode</code>
            to <code>FT_GLYPH_BBOX_TRUNCATE</code>.</p>

          <p>Finally, to get the bounding box in grid-fitted pixel
            coordinates, set <code>bbox_mode</code>
            to <code>FT_GLYPH_BBOX_PIXELS</code>.</p>

          <p>[Computing <em>exact</em> bounding boxes can be done with
            function <a href="../reference/ft2-outline_processing.html#ft_outline_get_bbox"><code>FT_Outline_Get_BBox</code></a>,
            at the cost of slower execution.  You probably don't need
            it with the possible exception of rotated glyphs.]</p>

          <h4>d. Converting the Glyph Image to a Bitmap</h4>

          <p>You may need to convert the glyph object to a bitmap once
            you have conveniently cached or transformed it.  This can
            be done easily with
            the <a href="../reference/ft2-glyph_management.html"><code>FT_Glyph_To_Bitmap</code></a>
            function, which handles any glyph object.</p>

          <pre>
FT_Vector  origin;


origin.x = 32; <span class="comment">/* 1/2 pixel in 26.6 format */</span>
origin.y = 0;

error = FT_Glyph_To_Bitmap(
          &amp;glyph,
          <em>render_mode</em>,
          &amp;origin,
          1 );          <span class="comment">/* destroy original image == true */</span></pre>

          <p>Some notes.</p>

          <ul>
            <li>The first parameter is the address of the source
              glyph's handle.  When the function is called, it reads
              it to access the source glyph object.  After the call,
              the handle points to a <em>new</em> glyph object that
              contains the rendered bitmap.</li>

            <li>The second parameter is a standard render mode to
              specify what kind of bitmap we want.  For example, it
              can be <code>FT_RENDER_MODE_DEFAULT</code> for an 8-bit
              anti-aliased pixmap, or <code>FT_RENDER_MODE_MONO</code>
              for a 1-bit monochrome bitmap.</li>

            <li>The third parameter is a pointer to a two-dimensional
              vector to translate the source glyph image before the
              conversion.  After the call, the source image is
              translated back to its original position (and is thus
              left unchanged).  If you do not need to translate the
              source glyph before rendering, set this pointer
              to NULL.</li>

            <li>The last parameter is a boolean that indicates whether
              the source glyph object should be destroyed by the
              function.  If false, the original glyph object is never
              destroyed, even if its handle is lost (it is up to
              client applications to keep it).</li>
          </ul>

          <p>The new glyph object always contains a bitmap (if no
            error is returned), and you must <em>typecast</em> its
            handle to the <code>FT_BitmapGlyph</code> type in order to
            access its content.  This type is a sort of
            &lsquo;subclass&rsquo; of <code>FT_Glyph</code> that
            contains additional fields
            (see <a href="../reference/ft2-glyph_management.html#ft_bitmapglyphrec"><code>FT_BitmapGlyphRec</code></a>).</p>

          <dl>
            <dt>left</dt>
            <dd>Just like the <code>bitmap_left</code> field of a
              glyph slot, this is the horizontal distance from the
              glyph origin (0,0) to the leftmost pixel of the glyph
              bitmap.  It is expressed in integer pixels.</dd>

            <dt>top</dt>
            <dd>Just like the <code>bitmap_top</code> field of a glyph
              slot, this is the vertical distance from the glyph
              origin (0,0) to the topmost pixel of the glyph bitmap
              (more precise, to the pixel just above the bitmap).
              This distance is expressed in integer pixels, and is
              positive for upwards&nbsp;y.</dd>

            <dt>bitmap</dt>
            <dd>This is a bitmap descriptor for the glyph object, just
              like the <code>bitmap</code> field in a glyph slot.</dd>
          </dl>


          <h3 id="section-3">3. Global Glyph Metrics</h3>

          <p>Unlike glyph metrics, global metrics are used to describe
            distances and features of a whole font face.  They can be
            expressed either in 26.6 pixel format or in (unscaled)
            font units for scalable formats.</p>

          <h4> a. Design global metrics</h4>

          <p>For scalable formats, all global metrics are expressed in
            font units in order to be later scaled to the device
            space, according to the rules described in the last
            section of this tutorial part.  You can access them
            directly as fields of an <code>FT_Face</code> handle.</p>

          <p>However, you need to check that the font face's format is
            scalable before using them.  One can do it with
            macro <code>FT_IS_SCALABLE</code>, which returns true when
            appropriate.</p>

          <p>Here a table of the global design metrics for scalable
            faces.</p>

          <dl>
            <dt>units_per_EM</dt>
            <dd>This is the size of the EM square for the font face.
              It is used by scalable formats to scale design
              coordinates to device pixels, as described in the last
              section of this tutorial part.  Its value usually is
              2048 (for TrueType) or 1000 (for Type&nbsp;1 or CFF),
              but other values are possible, too.  It is set to&nbsp;1
              for fixed-size formats like FNT, FON, PCF, or BDF.</dd>

            <dt>bbox</dt>
            <dd>The global bounding box is defined as the smallest
              rectangle that can enclose all the glyphs in a font
              face.</dd>

            <dt>ascender</dt>
            <dd>The ascender is the vertical distance from the
              horizontal baseline to the highest
              &lsquo;character&rsquo; coordinate in a font face.
              Unfortunately, font formats don't define the ascender in
              a uniform way.  For some formats, it represents the
              ascent of all capital latin characters (without
              accents), for others it is the ascent of the highest
              accented character, and finally, other formats define it
              as being equal to <code>bbox.yMax</code>.</dd>

            <dt>descender</dt>
            <dd>The descender is the vertical distance from the
              horizontal baseline to the lowest
              &lsquo;character&rsquo; coordinate in a font face.
              Unfortunately, font formats don't define the descender
              in a uniform way.  For some formats, it represents the
              descent of all capital latin characters (without
              accents), for others it is the ascent of the lowest
              accented character, and finally, other formats define it
              as being equal to <code>bbox.yMin</code>.  This field is
              negative for values below the baseline.</dd>

            <dt>height</dt>
            <dd>This field represents a <em>default line spacing</em>
              (i.e., the baseline-to-baseline distance) when writing
              text with this font.  Note that it usually is larger
              than the sum of the ascender and descender taken as
              absolute values.  There is also no guarantee that no
              glyphs extend above or below subsequent baselines when
              using this distance &ndash; think of it as a value the
              designer of the font finds appropriate.</dd>

            <dt>max_advance_width</dt>
            <dd>This field gives the maximum horizontal cursor advance
              for all glyphs in the font.  It can be used to quickly
              compute the maximum advance width of a string of
              text.  <em>It doesn't correspond to the maximum glyph
                image width!</em></dd>

            <dt>max_advance_height</dt>
            <dd>Same as <code>max_advance_width</code> but for
              vertical text layout.</dd>

            <dt>underline_position</dt>
            <dd>When displaying or rendering underlined text, this
              value corresponds to the vertical position, relative to
              the baseline, of the underline bar's center.  It is
              negative if it is below the baseline.</dd>

            <dt>underline_thickness</dt>
            <dd>When displaying or rendering underlined text, this
              value corresponds to the vertical thickness of the
              underline.</dd>
          </dl>

          <p>Notice that the values of the ascender and the descender
            are not reliable (due to various discrepancies in font
            formats), unfortunately.</p>

          <h4>b. Scaled Global Metrics</h4>

          <p>Each size object also contains a scaled version of some
            of the global metrics described above, to be directly
            accessed through
            the <code>face-&gt;size-&gt;metrics</code> structure (of
            type <a href="../reference/ft2-base_interface.html#ft_size_metrics">
              <code>FT_Size_Metrics</code></a>).  <em>No grid-fitting
            is performed for those values</em>.  They are also
            completely independent of any hinting process.  In other
            words, don't rely on them to get exact metrics at the
            pixel level.  They are expressed in 26.6 pixel format but
            rounded for historical reasons.</p>

          <dl>
            <dt>ascender</dt>
            <dd>The scaled version of the original design ascender;
              rounded up to an integer value.</dd>

            <dt>descender</dt>
            <dd>The scaled version of the original design descender,
              rounded down to an integer value.</dd>

            <dt>height</dt>
            <dd>
              <p>The scaled version of the original design text height
                (the vertical distance from one baseline to the next).
                This is probably the only field you should really use
                in this structure.  It is rounded to an integer
                value.</p>

              <p>Be careful not to confuse it with the
                &lsquo;height&rsquo; field in
                the <a href="../reference/ft2-base_interface.html#ft_glyph_metrics"><code>FT_Glyph_Metrics</code></a>
                structure.</p>
            </dd>

            <dt>max_advance</dt>
            <dd>The scaled version of the original design maximum
              advance, rounded to an integer value.</dd>
          </dl>

          <p>Note that the <code>face-&gt;size-&gt;metrics</code>
            structure contains other fields that are used to scale
            design coordinates to device space.  They are described in
            the last section.</p>

          <h4>c. Kerning</h4>

          <p>Kerning is the process of adjusting the position of two
            subsequent glyph images in a string of text in order to
            improve the general appearance of text.  For example, if a
            glyph for an uppercase &lsquo;A&rsquo; is followed by a
            glyph for an uppercase &lsquo;V&rsquo;, the space between
            the two glyphs can be slightly reduced to avoid extra
            &lsquo;diagonal whitespace&rsquo;.</p>

          <p>Note that in theory kerning can happen both in the
            horizontal and vertical direction between two glyphs;
            however, it only happens in a single direction in nearly
            all cases.</p>

          <p>Not all font formats contain kerning information, and not
            all kerning formats are supported by FreeType; in
            particular, for TrueType fonts, the API can only access
            kerning via the &lsquo;kern&rsquo;
            table.  <span class="important">OpenType kerning via the
            &lsquo;GPOS&rsquo; table is not supported!</span>  You
            need a higher-level library
            like <a href="http://www.harfbuzz.org">HarfBuzz</a>,
            <a href="http://www.pango.org">Pango</a>,
            or <a href="http://www.icu-project.org">ICU</a>, since
            GPOS kerning requires contextual string handling.</p>

          <p>Sometimes, the font file is associated with an additional
            file that contains various glyph metrics, including
            kerning, but no glyph images.  A good example is the
            Type&nbsp;1 format where glyph images are stored in files
            with extension <code>.pfa</code> or <code>.pfb</code>,
            while kerning metrics can be found in files with extension
            <code>.afm</code> or <code>.pfm</code>.</p>

          <p>FreeType&nbsp;2 allows you to deal with this, by
            providing
            the <a href="../reference/ft2-base_interface.html#ft_attach_file"><code>FT_Attach_File</code></a>
            and <a href="../reference/ft2-base_interface.html#ft_attach_stream"><code>FT_Attach_Stream</code></A>
            APIs.  Both functions are used to load additional metrics
            into a face object by reading them from an additional
            format-specific file.  Here an example, opening a
            Type&nbsp;1 font.</p>

          <pre>
error = FT_New_Face( library, "/usr/share/fonts/cour.pfb",
                     0, &amp;face );
if ( error ) { ... }

error = FT_Attach_File( face, "/usr/share/fonts/cour.afm" );
if ( error )
{ ... could not read kerning and additional metrics ... }</pre>

          <p>Note that <code>FT_Attach_Stream</code> is similar to
            <code>FT_Attach_File</code> except that it doesn't take a
            C&nbsp;string to name the extra file but
            an <a href="../reference/ft2-system_interface.html#ft_streamrec"><code>FT_Stream</code></a>
            handle.  Also, <em>reading a metrics file is in no way
            mandatory</em>.</p>

          <p>Finally, the file attachment APIs are very generic and
            can be used to load any kind of extra information for a
            given face.  The nature of the additional content is
            entirely font format specific.</p>

          <p>FreeType&nbsp;2 allows you to retrieve the kerning
            information between two glyphs through
            the <a href="../reference/ft2-base_interface.html#ft_get_kerning"><code>FT_Get_Kerning</code></a>
            function.</p>

          <pre>
FT_Vector  kerning;


...
error = FT_Get_Kerning( face,          <span class="comment">/* handle to face object */</span>
                        left,          <span class="comment">/* left glyph index      */</span>
                        right,         <span class="comment">/* right glyph index     */</span>
                        <em>kerning_mode</em>,  <span class="comment">/* kerning mode          */</span>
                        &amp;kerning );    <span class="comment">/* target vector         */</span></pre>

          <p>This function takes a handle to a face object, the
            indices of the left and right glyph for which the kerning
            value is desired, an integer, called the <em>kerning
            mode</em>, and a pointer to a destination vector that
            receives the corresponding distances.</p>

          <p>The kerning mode is very similar to the <em>bbox
            mode</em> described in a previous section.  It is a
            enumeration that indicates how the kerning distances are
            expressed in the target vector.</p>

          <p>The default value is <code>FT_KERNING_DEFAULT</code>,
            which has value&nbsp;0.  It corresponds to kerning
            distances expressed in 26.6 grid-fitted pixels (which
            means that the values are multiples of 64).  For scalable
            formats, this means that the design kerning distance is
            scaled, then rounded.</p>

          <p>The value <code>FT_KERNING_UNFITTED</code> corresponds to
            kerning distances expressed in 26.6 unfitted pixels (i.e.,
            that do not correspond to integer coordinates).  It is the
            design kerning distance that is scaled without
            rounding.</p>

          <p>Finally, the value <code>FT_KERNING_UNSCALED</code>
            indicates to return the design kerning distance, expressed
            in font units.  You can later scale it to the device space
            using the computations explained in the last section of
            this part.</p>

          <p>Note that the &lsquo;left&rsquo; and &lsquo;right&rsquo;
            positions correspond to the <em>visual order</em> of the
            glyphs in the string of text.  This is important for
            bidirectional or right-to-left text.</p>


          <h3 id="section-4">4. Simple Text Rendering: Kerning and Centering</h3>

          <p>In order to show off what we have just learned, we now
            demonstrate how to modify
            the <a href="step1.html#basic-code">example code</a> that
            was provided in part&nbsp;I to render a string of text,
            and enhance it to support kerning and delayed
            rendering.</p>

          <h4>a. Kerning Support</h4>

          <p>Adding support for kerning to our code is trivial, as
            long as we consider that we are still dealing with a
            left-to-right script like Latin.  We simply need to
            retrieve the kerning distance between two glyphs in order
            to alter the pen position appropriately.</p>

          <pre>
FT_GlyphSlot  slot = face-&gt;glyph;  <span class="comment">/* a small shortcut */</span>
FT_UInt       glyph_index;
FT_Bool       use_kerning;
FT_UInt       previous;
int           pen_x, pen_y, n;


... initialize library ...
... create face object ...
... set character size ...

pen_x = 300;
pen_y = 200;

use_kerning = FT_HAS_KERNING( face );
previous    = 0;

for ( n = 0; n &lt; num_chars; n++ )
{
  <span class="comment">/* convert character code to glyph index */</span>
  glyph_index = FT_Get_Char_Index( face, text[n] );

  <span class="comment">/* retrieve kerning distance and move pen position */</span>
  if ( use_kerning &amp;&amp; previous &amp;&amp; glyph_index )
  {
    FT_Vector  delta;


    FT_Get_Kerning( face, previous, glyph_index,
                    FT_KERNING_DEFAULT, &amp;delta );

    pen_x += delta.x &gt;&gt; 6;
  }

  <span class="comment">/* load glyph image into the slot (erase previous one) */</span>
  error = FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER );
  if ( error )
    continue;  <span class="comment">/* ignore errors */</span>

  <span class="comment">/* now draw to our target surface */</span>
  my_draw_bitmap( &amp;slot-&gt;bitmap,
                  pen_x + slot-&gt;bitmap_left,
                  pen_y - slot-&gt;bitmap_top );

  <span class="comment">/* increment pen position */</span>
  pen_x += slot->advance.x &gt;&gt; 6;

  <span class="comment">/* record current glyph index */</span>
  previous = glyph_index;
}</pre>

          <p>We are done.  Some notes.</p>

          <ul>
            <li>As kerning is determined by glyph indices, we need to
              explicitly convert our character codes into glyph
              indices, then later call <code>FT_Load_Glyph</code>
              instead of <code>FT_Load_Char</code>.</li>

            <li>We use a boolean named <code>use_kerning</code>, which
              is set to the result of the
              macro <code>FT_HAS_KERNING</code>.  It is certainly
              faster not to call <code>FT_Get_Kerning</code> when we
              know that the font face does not contain kerning
              information.</li>

            <li>We move the position of the pen <em>before</em> a new
              glyph is drawn.</li>

            <li>We initialize the variable <code>previous</code> with
              the value&nbsp;0, which always corresponds to the
              &lsquo;missing glyph&rsquo; (also
              called <code>.notdef</code> in the PostScript world).
              There is never any kerning distance associated with this
              glyph.</li>

            <li>We do not check the error code returned by
              <code>FT_Get_Kerning</code>.  This is because the
              function always sets the content of <code>delta</code>
              to (0,0) if an error occurs.</li>
          </ul>

          <h4>b. Centering</h4>

          <p>Our code begins to become interesting but it is still a
            bit too simple for normal use.  For example, the position
            of the pen is determined before we do the rendering;
            normally, you would rather determine the layout of the
            text and measure it before computing its final position
            (centering, etc.), or perform things like
            word-wrapping.</p>

          <p>Let us now decompose our text rendering function into two
            distinct but successive parts: The first one positions
            individual glyph images on the baseline, while the second
            one renders the glyphs.  As we will see, this has many
            advantages.</p>

          <p>We thus start by storing individual glyph images, as well
            as their position on the baseline.</p>

          <pre>
FT_GlyphSlot  slot = face-&gt;glyph;   <span class="comment">/* a small shortcut */</span>
FT_UInt       glyph_index;
FT_Bool       use_kerning;
FT_UInt       previous;
int           pen_x, pen_y, n;

FT_Glyph      glyphs[MAX_GLYPHS];   <span class="comment">/* glyph image    */</span>
FT_Vector     pos   [MAX_GLYPHS];   <span class="comment">/* glyph position */</span>
FT_UInt       num_glyphs;


... initialize library ...
... create face object ...
... set character size ...

pen_x = 0;   <span class="comment">/* start at (0,0) */</span>
pen_y = 0;

num_glyphs  = 0;
use_kerning = FT_HAS_KERNING( face );
previous    = 0;

for ( n = 0; n &lt; num_chars; n++ )
{
  <span class="comment">/* convert character code to glyph index */</span>
  glyph_index = FT_Get_Char_Index( face, text[n] );

  <span class="comment">/* retrieve kerning distance and move pen position */</span>
  if ( use_kerning &amp;&amp; previous &amp;&amp; glyph_index )
  {
    FT_Vector  delta;


    FT_Get_Kerning( face, previous, glyph_index,
                    FT_KERNING_DEFAULT, &amp;delta );

    pen_x += delta.x &gt;&gt; 6;
  }

  <span class="comment">/* store current pen position */</span>
  pos[num_glyphs].x = pen_x;
  pos[num_glyphs].y = pen_y;

  <span class="comment">/* load glyph image into the slot without rendering */</span>
  error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );
  if ( error )
    continue;  <span class="comment">/* ignore errors, jump to next glyph */</span>

  <span class="comment">/* extract glyph image and store it in our table */</span>
  error = FT_Get_Glyph( face-&gt;glyph, &amp;glyphs[num_glyphs] );
  if ( error )
    continue;  <span class="comment">/* ignore errors, jump to next glyph */</span>

  <span class="comment">/* increment pen position */</span>
  pen_x += slot->advance.x &gt;&gt; 6;

  <span class="comment">/* record current glyph index */</span>
  previous = glyph_index;

  <span class="comment">/* increment number of glyphs */</span>
  num_glyphs++;
}</pre>

          <p>This is a very slight variation of our previous code; we
            extract each glyph image from the slot, then store it,
            along with the corresponding position, in our tables.</p>

          <p>Note also that <code>pen_x</code> contains the total
            advance for the string of text.  We can now compute the
            bounding box of the text string with a simple
            function.</p>

          <pre>
void  compute_string_bbox( FT_BBox  *abbox )
{
  FT_BBox  bbox;
  FT_BBox  glyph_bbox;


  <span class="comment">/* initialize string bbox to "empty" values */</span>
  bbox.xMin = bbox.yMin =  32000;
  bbox.xMax = bbox.yMax = -32000;

  <span class="comment">/* for each glyph image, compute its bounding box, */</span>
  <span class="comment">/* translate it, and grow the string bbox          */</span>
  for ( n = 0; n &lt; num_glyphs; n++ )
  {
    FT_Glyph_Get_CBox( glyphs[n], ft_glyph_bbox_pixels,
                       &amp;glyph_bbox );

    glyph_bbox.xMin += pos[n].x;
    glyph_bbox.xMax += pos[n].x;
    glyph_bbox.yMin += pos[n].y;
    glyph_bbox.yMax += pos[n].y;

    if ( glyph_bbox.xMin &lt; bbox.xMin )
      bbox.xMin = glyph_bbox.xMin;

    if ( glyph_bbox.yMin &lt; bbox.yMin )
      bbox.yMin = glyph_bbox.yMin;

    if ( glyph_bbox.xMax &gt; bbox.xMax )
      bbox.xMax = glyph_bbox.xMax;

    if ( glyph_bbox.yMax &gt; bbox.yMax )
      bbox.yMax = glyph_bbox.yMax;
  }

  <span class="comment">/* check that we really grew the string bbox */</span>
  if ( bbox.xMin &gt; bbox.xMax )
  {
    bbox.xMin = 0;
    bbox.yMin = 0;
    bbox.xMax = 0;
    bbox.yMax = 0;
  }

  <span class="comment">/* return string bbox */</span>
  *abbox = bbox;
}</pre>

          <p>The resulting bounding box dimensions are expressed in
            integer pixels and can then be used to compute the final
            pen position before rendering the string.</p>

          <p class="warning">In general, the above function
            does <em>not</em> compute an exact bounding box of a
            string!  As soon as hinting is involved, glyph
            dimensions <em>must</em> be derived from the resulting
            outlines.  For anti-aliased pixmaps,
            <code>FT_Outline_Get_BBox</code> then yields proper
            results.  In case you need 1-bit monochrome bitmaps, it is
            even necessary to actually render the glyphs because the
            rules for the conversion from outline to bitmap can also
            be controlled by hinting instructions
            (cf. <a href="https://docs.microsoft.com/en-us/typography/opentype/spec/ttch01#the-scan-converter">dropout
            control</a>).</p>

          <pre>
<span class="comment">/* compute string dimensions in integer pixels */</span>
string_width  = string_bbox.xMax - string_bbox.xMin;
string_height = string_bbox.yMax - string_bbox.yMin;

<span class="comment">/* compute start pen position in 26.6 Cartesian pixels */</span>
start_x = ( ( my_target_width  - string_width  ) / 2 ) * 64;
start_y = ( ( my_target_height - string_height ) / 2 ) * 64;

for ( n = 0; n &lt; num_glyphs; n++ )
{
  FT_Glyph   image;
  FT_Vector  pen;


  image = glyphs[n];

  pen.x = start_x + pos[n].x;
  pen.y = start_y + pos[n].y;

  error = FT_Glyph_To_Bitmap( &amp;image, FT_RENDER_MODE_NORMAL,
                              &amp;pen, 0 );
  if ( !error )
  {
    FT_BitmapGlyph  bit = (FT_BitmapGlyph)image;


    my_draw_bitmap( bit-&gt;bitmap,
                    bit-&gt;left,
                    my_target_height - bit-&gt;top );

    FT_Done_Glyph( image );
  }
}</pre>

          <p>Some remarks.</p>

          <ul>
            <li>The pen position is expressed in the Cartesian space
              (i.e., y&nbsp;upwards).</li>

            <li>We call <code>FT_Glyph_To_Bitmap</code> with
              the <code>destroy</code> parameter set to&nbsp;0
              (false), in order to avoid destroying the original glyph
              image.  The new glyph bitmap is accessed through
              <code>image</code> after the call and is typecast to
              <code>FT_BitmapGlyph</code>.</li>

            <li>We use translation when
              calling <code>FT_Glyph_To_Bitmap</code>.  This ensures
              that the <code>left</code> and <code>top</code> fields
              of the bitmap glyph object are already set to the
              correct pixel coordinates in the Cartesian space.</li>

            <li>Of course, we still need to convert pixel coordinates
              from Cartesian to device space before rendering, hence
              the <code>my_target_height - bitmap->top</code> in the
              call to <code>my_draw_bitmap</code>.</li>
          </ul>

          <p>The same loop can be used to render the string anywhere
            on our display surface, without the need to reload our
            glyph images each time.</p>


          <h3 id="section-5">5. Advanced Text Rendering:
            Transformation and Centering and Kerning</h3>

          <p>We are now going to modify our code in order to be able
            to easily transform the rendered string, for example, to
            rotate it.  First, some minor improvements.</p>

          <h4>a. Packing and Translating Glyphs</h4>

          <p>We start by packing the information related to a single
            glyph image into a single structure instead of parallel
            arrays.</p>

          <pre>
typedef struct  TGlyph_
{
  FT_UInt    index;  <span class="comment">/* glyph index                  */</span>
  FT_Vector  pos;    <span class="comment">/* glyph origin on the baseline */</span>
  FT_Glyph   image;  <span class="comment">/* glyph image                  */</span>

} TGlyph, *PGlyph;</pre>

          <p>We also translate each glyph image directly after it is
            loaded to its position on the baseline at load time.  As
            we will see, this has several advantages.  Here is our new
            glyph sequence loader.</p>

          <pre>
FT_GlyphSlot  slot = face-&gt;glyph;  <span class="comment">/* a small shortcut */</span>
FT_UInt       glyph_index;
FT_Bool       use_kerning;
FT_UInt       previous;
int           pen_x, pen_y, n;

TGlyph        glyphs[MAX_GLYPHS];  <span class="comment">/* glyphs table */</span>
PGlyph        glyph;               <span class="comment">/* current glyph in table */</span>
FT_UInt       num_glyphs;


... initialize library ...
... create face object ...
... set character size ...

pen_x = 0;   <span class="comment">/* start at (0,0) */</span>
pen_y = 0;

num_glyphs  = 0;
use_kerning = FT_HAS_KERNING( face );
previous    = 0;

glyph = glyphs;
for ( n = 0; n &lt; num_chars; n++ )
{
  glyph-&gt;index = FT_Get_Char_Index( face, text[n] );

  if ( use_kerning &amp;&amp; previous &amp;&amp; glyph->index )
  {
    FT_Vector  delta;


    FT_Get_Kerning( face, previous, glyph-&gt;index,
                    FT_KERNING_MODE_DEFAULT, &amp;delta );

    pen_x += delta.x &gt;&gt; 6;
  }

  <span class="comment">/* store current pen position */</span>
  glyph->pos.x = pen_x;
  glyph->pos.y = pen_y;

  error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );
  if ( error ) continue;

  error = FT_Get_Glyph( face-&gt;glyph, &amp;glyph-&gt;image );
  if ( error ) continue;

  <span class="comment">/* translate the glyph image now */</span>
  FT_Glyph_Transform( glyph-&gt;image, 0, &amp;glyph-&gt;pos );

  pen_x   += slot->advance.x &gt;&gt; 6;
  previous = glyph->index;

  <span class="comment">/* increment number of glyphs */</span>
  glyph++;
}

<span class="comment">/* count number of glyphs loaded */</span>
num_glyphs = glyph - glyphs;</pre>

          <p>Note that translating glyphs now has several advantages.
            The first one is that we don't need to translate the glyph
            bbox when we compute the string's bounding box.</p>

          <pre>
void  compute_string_bbox( FT_BBox  *abbox )
{
  FT_BBox  bbox;


  bbox.xMin = bbox.yMin =  32000;
  bbox.xMax = bbox.yMax = -32000;

  for ( n = 0; n &lt; num_glyphs; n++ )
  {
    FT_BBox  glyph_bbox;


    FT_Glyph_Get_CBox( glyphs[n], ft_glyph_bbox_pixels,
                       &amp;glyph_bbox );

    if (glyph_bbox.xMin &lt; bbox.xMin)
      bbox.xMin = glyph_bbox.xMin;

    if (glyph_bbox.yMin &lt; bbox.yMin)
      bbox.yMin = glyph_bbox.yMin;

    if (glyph_bbox.xMax &gt; bbox.xMax)
      bbox.xMax = glyph_bbox.xMax;

    if (glyph_bbox.yMax &gt; bbox.yMax)
      bbox.yMax = glyph_bbox.yMax;
  }

  if ( bbox.xMin > bbox.xMax )
  {
    bbox.xMin = 0;
    bbox.yMin = 0;
    bbox.xMax = 0;
    bbox.yMax = 0;
  }

  *abbox = bbox;
}</pre>

          <p>With the above modifications,
            the <code>compute_string_bbox</code> function can now
            compute the bounding box of a transformed glyph string,
            which allows further code simplications.</p>

          <pre>
FT_BBox    bbox;
FT_Matrix  matrix;
FT_Vector  delta;


... load glyph sequence ...
... set up `matrix' and `delta' ...

<span class="comment">/* transform glyphs */</span>
for ( n = 0; n &lt; num_glyphs; n++ )
  FT_Glyph_Transform( glyphs[n].image, &amp;matrix, &amp;delta );

<span class="comment">/* compute bounding box of transformed glyphs */</span>
compute_string_bbox( &amp;bbox );</pre>

          <h4>b. Rendering a Transformed Glyph Sequence</h4>

          <p>However, directly transforming the glyphs in our sequence
            is not a good idea if we want to reuse them in order to
            draw the text string with various angles or
            transformations.  It is better to perform the affine
            transformation just before the glyph is rendered.</p>

          <pre>
FT_Vector  start;
FT_Matrix  matrix;

FT_Glyph   image;
FT_Vector  pen;
FT_BBox    bbox;


<span class="comment">/* get bbox of original glyph sequence */</span>
compute_string_bbox( &amp;string_bbox );

<span class="comment">/* compute string dimensions in integer pixels */</span>
string_width  = (string_bbox.xMax - string_bbox.xMin) / 64;
string_height = (string_bbox.yMax - string_bbox.yMin) / 64;

<span class="comment">/* set up start position in 26.6 Cartesian space */</span>
start.x = ( ( my_target_width  - string_width  ) / 2 ) * 64;
start.y = ( ( my_target_height - string_height ) / 2 ) * 64;

<span class="comment">/* set up transform (a rotation here) */</span>
matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L );
matrix.xy = (FT_Fixed)(-sin( angle ) * 0x10000L );
matrix.yx = (FT_Fixed)( sin( angle ) * 0x10000L );
matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L );

pen = start;

for ( n = 0; n &lt; num_glyphs; n++ )
{
  <span class="comment">/* create a copy of the original glyph */</span>
  error = FT_Glyph_Copy( glyphs[n].image, &amp;image );
  if ( error ) continue;

  <span class="comment">/* transform copy (this will also translate it to the */</span>
  <span class="comment">/* correct position                                   */</span>
  FT_Glyph_Transform( image, &amp;matrix, &amp;pen );

  <span class="comment">/* check bounding box; if the transformed glyph image      */</span>
  <span class="comment">/* is not in our target surface, we can avoid rendering it */</span>
  FT_Glyph_Get_CBox( image, ft_glyph_bbox_pixels, &amp;bbox );
  if ( bbox.xMax &lt;= 0 || bbox.xMin &gt;= my_target_width  ||
       bbox.yMax &lt;= 0 || bbox.yMin &gt;= my_target_height )
    continue;

  <span class="comment">/* convert glyph image to bitmap (destroy the glyph copy!) */</span>
  error = FT_Glyph_To_Bitmap(
            &amp;image,
            FT_RENDER_MODE_NORMAL,
            0,                  <span class="comment">/* no additional translation */</span>
            1 );                <span class="comment">/* destroy copy in "image"   */</span>
  if ( !error )
  {
    FT_BitmapGlyph  bit = (FT_BitmapGlyph)image;


    my_draw_bitmap( bit-&gt;bitmap,
                    bit-&gt;left,
                    my_target_height - bit-&gt;top );

    <span class="comment">/* increment pen position --                       */</span>
    <span class="comment">/* we don't have access to a slot structure,       */</span>
    <span class="comment">/* so we have to use advances from glyph structure */</span>
    <span class="comment">/* (which are in 16.16 fixed float format)         */</span>
    pen.x += image.advance.x >> 10;
    pen.y += image.advance.y >> 10;

    FT_Done_Glyph( image );
  }
}</pre>

          <p>There are a few changes compared to the original version
            of this code.</p>

          <ul>
            <li>We keep the original glyph images untouched; instead,
              we transform a copy.</li>

            <li>We perform clipping computations in order to avoid
              rendering and drawing glyphs that are not within our
              target surface.</li>

            <li>We always destroy the copy when calling
              <code>FT_Glyph_To_Bitmap</code> in order to get rid of
              the transformed scalable image.  Note that the image is
              not destroyed if the function returns an error code
              (which is why <code>FT_Done_Glyph</code> is only called
              within the compound statement).</li>

            <li>The translation of the glyph sequence to the start pen
              position is integrated into the call
              to <code>FT_Glyph_Transform</code> instead
              of <code>FT_Glyph_To_Bitmap</code>.</li>
          </ul>

          <p>It is possible to call this function several times to
            render the string with different angles, or even change
            the way <code>start</code> is computed in order to move it
            to different place.</p>

          <p>This code is the basis of the FreeType&nbsp;2
            demonstration program
            named <a href="http://git.savannah.gnu.org/cgit/freetype/freetype2-demos.git/tree/src/ftstring.c"><code>ftstring.c</code></a>.
            It could be easily extended to perform advanced text
            layout or word-wrapping in the first part, without
            changing the second one.</p>

          <p>Note, however, that a normal implementation would use a
            glyph cache in order to reduce memory needs.  For example,
            let us assume that our text string is
            &lsquo;FreeType&rsquo;.  We would store three identical
            glyph images in our table for the letter &lsquo;e&rsquo;,
            which isn't optimal (especially when you consider longer
            lines of text, or even whole pages).</p>

          <p>A FreeType demo program that shows how glyph caching can
            be implemented
            is <a href="http://git.savannah.gnu.org/cgit/freetype/freetype2-demos.git/tree/src/ftview.c"><code>ftview.c</code></a>.
            In general, &lsquo;ftview&rsquo; is the main program used
            by the FreeType developer team to check the validity of
            loading, parsing, and rendering fonts.</p>

          <p>Another very useful demo program
            is <a href="http://git.savannah.gnu.org/cgit/freetype/freetype2-demos.git/tree/src/ftdiff.c"><code>ftdiff.c</code></a>,
            demonstrating the use and the optical results of the
            various rendering and hinting modes provided by FreeType.
            In particular, it also demonstrates how to do sub-pixel
            positioning (for unhinted glyphs and &lsquo;light&rsquo;
            hinting mode) &ndash; all code in this tutorial assumes
            integer coordinates.</p>


          <h3 id="section-6">6. Accessing Metrics in Design Font
            Units, and Scaling Them</h3>

          <p>Scalable font formats usually store a single vectorial
            image, called an <em>outline</em>, for each glyph in a
            face.  Each outline is defined in an abstract grid called
            the <em>design space</em>, with coordinates expressed in
            <em>font units</em>.  When a glyph image is loaded, the
            font driver usually scales the outline to device space
            according to the current character pixel size found in
            an <a href="../reference/ft2-base_interface.html#ft_size"><code>FT_Size</code></a>
            object.  The driver may also modify the scaled outline in
            order to significantly improve its appearance on a
            pixel-based surface (a process known as <em>hinting</em>
            or <em>grid-fitting</em>).</p>

          <p>This section describes how design coordinates are scaled
            to the device space, and how to read glyph outlines and
            metrics in font units.  This is important for a number of
            things.</p>

          <ul>
            <li>&lsquo;True&rsquo; WYSIWYG text layout.</li>
            <li>Accessing font content for conversion or analysis
              purposes.</li>
          </ul>

          <h4>a. Scaling Distances to Device Space</h4>

          <p>Design coordinates are scaled to the device space using a
            simple scaling transformation whose coefficients are
            computed with the help of the <em>character pixel
            size</em>.</p>

          <pre class="example">
  device_x = design_x * x_scale
  device_y = design_y * y_scale

  x_scale  = pixel_size_x / EM_size
  y_scale  = pixel_size_y / EM_size</pre>

          <p>Here, the value <code>EM_size</code> is font-specific and
            corresponds to the size of an abstract square of the
            design space (called the <em>EM</em>), which is used by
            font designers to create glyph images.  It is thus
            expressed in font units.  It is also accessible directly
            for scalable font formats
            as <code>face-&gt;units_per_EM</code>.  You should check
            that a font face contains scalable glyph images by using
            the <code>FT_IS_SCALABLE</code> macro, which returns true
            if appropriate.</p>

          <p>When you call the
            function <a href="../reference/ft2-base_interface.html#ft_set_pixel_sizes"><code>FT_Set_Pixel_Sizes</code></a>,
            you are specifying integer values
            of <code>pixel_size_x</code> and
            <code>pixel_size_y</code> FreeType shall use.  The library
            will immediately compute the values
            of <code>x_scale</code> and
            <code>y_scale</code>.</p>

          <p>When you call the
            function <a href="../reference/ft2-base_interface.html#ft_set_char_size"><code>FT_Set_Char_Size</code></a>,
            you are specifying the character size in
            physical <em>points</em>, which is used, along with the
            device's resolutions, to compute the character pixel size
            and the corresponding scaling factors.  Here, the scaling
            factors can correspond to fractional ppem values.</p>

          <p>Note that after calling any of these two functions, you
            can access the values of the character pixel size and
            scaling factors as fields of
            the <code>face-&gt;size-&gt;metrics</code> structure.</p>

          <dl>
            <dt>x_ppem</dt>
            <dd>The field name stands for &lsquo;x&nbsp;pixels per
              EM&rsquo;; this is the horizontal size rounded to
              integer pixels of the EM square, which also is
              the <em>horizontal character pixel size</em>,
              called <code>pixel_size_x</code> in the above
              example.</dd>

            <dt>y_ppem</dt>
            <dd>The field name stands for &lsquo;y&nbsp;pixels per
              EM&rsquo;; this is the vertical size rounded to integer
              pixels of the EM square, which also is the <em>vertical
              character pixel size</em>,
              called <code>pixel_size_y</code> in the above
              example.</dd>

            <dt>x_scale</dt>
            <dd>This is a 16.16 fixed-point scale to directly scale
              horizontal distances from design space to 1/64th of
              device pixels.</dd>

            <dt>y_scale</dt>
            <dd>This is a 16.16 fixed-point scale to directly scale
              vertical distances from design space to 1/64th of device
              pixels.</dd>
          </dl>

          <p>You can scale a distance expressed in font units to 26.6
            pixel format directly with the help of
            the <a href="../reference/ft2-computations.html#ft_mulfix"><code>FT_MulFix</code></a>
            function.</p>

          <pre>
<span class="comment">/* convert design distances to 1/64th of pixels */</span>
pixels_x = FT_MulFix( design_x, face-&gt;size-&gt;metrics.x_scale );
pixels_y = FT_MulFix( design_y, face-&gt;size-&gt;metrics.y_scale );</pre>

          <p>Alternatively, you can also scale the value directly by
            using doubles.</p>

          <pre>
FT_Size_Metrics*  metrics = &amp;face-&gt;size-&gt;metrics; <span class="comment">/* shortcut */</span>
double            pixels_x, pixels_y;
double            x_scale, y_scale;


<span class="comment">/* compute floating point scale factors */</span>
x_scale = face-&gt;size-&gt;metrics.x_scale / 65536.0;
y_scale = face-&gt;size-&gt;metrics.y_scale / 65536.0;

<span class="comment">/* convert design distances to floating point pixels */</span>
pixels_x = design_x * x_scale;
pixels_y = design_y * y_scale;</pre>

          <h4>b. Accessing Design Metrics (Glyph &amp; Global)</h4>

          <p>You can access glyph metrics in font units simply by
            specifying the <code>FT_LOAD_NO_SCALE</code> bit flag
            in <code>FT_Load_Glyph</code>
            or <code>FT_Load_Char</code>.  The metrics returned
            in <code>face-&gt;glyph-&gt;metrics</code> will all be in
            font units.</p>

          <p>You can access unscaled kerning data using the
            <code>FT_KERNING_MODE_UNSCALED</code> mode.</p>

          <p>Finally, a few global metrics are available directly in
            font units as fields of the <code>FT_Face</code> handle,
            as described in <a href="#section-3">section&nbsp;3</a> of
            this part.</p>


          <h3 id="conclusion">Conclusion</h3>

          <p>This is the end of the second part of the FreeType
            tutorial.  You are now able to access glyph metrics,
            manage glyph images, and render text much more
            intelligently (kerning, measuring, transforming &amp;
            caching); this is sufficient knowledge to build a pretty
            decent text service on top of FreeType.</p>

          <p>The demo programs in the &lsquo;ft2demos&rsquo; bundle
            (especially &lsquo;ftview&rsquo;) are a kind of reference
            implementation, and are a good resource to turn to for
            answers.  They also show how to use additional features,
            such as the glyph stroker and cache.</p>
        </div>

        <!-- ************************************************** -->

        <div class="updated">
          <p>Last update: 13-Feb-2018</p>
        </div>
      </div>
    </div>


    <!-- ************************************************** -->

    <div class="col2">
    </div>
  </div>
</div>


<!-- ************************************************** -->

<div id="TOC">
  <ul>
<!--    <li class="funding">
      <form action="https://www.paypal.com/cgi-bin/webscr"
            method="post"
            target="_top">
        <input type="hidden"
               name="cmd"
               value="_s-xclick">
        <input type="hidden"
               name="hosted_button_id"
               value="SK827YKEALMT4">
        <input type="image"
               src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif"
               name="submit"
               alt="PayPal - The safer, easier way to pay online!">
        <img alt=""
             border="0"
             src="https://www.paypalobjects.com/de_DE/i/scr/pixel.gif"
             width="1"
             height="1">
      </form>
    </li>-->
    <li class="primary">
      <a href="http://freetype.org/index.html">Home</a>
    </li>
    <li class="primary">
      <a href="http://freetype.org/index.html#news">News</a>
    </li>
    <li class="primary">
      <a href="../index.html">Overview</a>
    </li>
    <li class="primary">
      <a href="../documentation.html">Documentation</a>
    </li>
    <li class="primary">
      <a href="http://freetype.org/developer.html">Development</a>
    </li>
    <li class="primary">
      <a href="http://freetype.org/contact.html"
         class="emphasis">Contact</a>
    </li>

    <li>
      &nbsp; <!-- separate primary from secondary entries -->
    </li>

    <li class="secondary">
      <a href="index.html">FreeType Tutorial</a>
    </li>
    <li class="tertiary">
      <a href="step1.html">Simple Glyph Loading</a>
    </li>
    <li class="tertiary">
      <a href="step2.html" class="current">Managing Glyphs</a>
    </li>
    <li class="tertiary">
      <a href="step3.html">Examples</a>
    </li>
  </ul>
</div>

</div> <!-- id="wrapper" -->

<div id="TOC-bottom">
</div>

</body>
</html>