Skip to content

FreeType » Docs » Core API » Glyph Retrieval

# Glyph Retrieval

## Synopsis

The functions and structures collected in this section operate on single glyphs, of which `FT_Load_Glyph` is most important.

## FT_GlyphSlot

Defined in FT_FREETYPE_H (freetype/freetype.h).

      typedef struct FT_GlyphSlotRec_*  FT_GlyphSlot;

A handle to a given ‘glyph slot’. A slot is a container that can hold any of the glyphs contained in its parent face.

In other words, each time you call `FT_Load_Glyph` or `FT_Load_Char`, the slot's content is erased by the new glyph data, i.e., the glyph's metrics, its image (bitmap or outline), and other control information.

#### also

See `FT_GlyphSlotRec` for the publicly accessible glyph fields.

## FT_GlyphSlotRec

Defined in FT_FREETYPE_H (freetype/freetype.h).

      typedef struct  FT_GlyphSlotRec_
      {
        FT_Library        library;
        FT_Face           face;
        FT_GlyphSlot      next;
        FT_UInt           glyph_index; /* new in 2.10; was reserved previously */
        FT_Generic        generic;

        FT_Glyph_Metrics  metrics;
        FT_Fixed          linearHoriAdvance;
        FT_Fixed          linearVertAdvance;
        FT_Vector         advance;

        FT_Glyph_Format   format;

        FT_Bitmap         bitmap;
        FT_Int            bitmap_left;
        FT_Int            bitmap_top;

        FT_Outline        outline;

        FT_UInt           num_subglyphs;
        FT_SubGlyph       subglyphs;

        void*             control_data;
        long              control_len;

        FT_Pos            lsb_delta;
        FT_Pos            rsb_delta;

        void*             other;

        FT_Slot_Internal  internal;

      } FT_GlyphSlotRec;

FreeType root glyph slot class structure. A glyph slot is a container where individual glyphs can be loaded, be they in outline or bitmap format.

#### fields

library | A handle to the FreeType library instance this slot belongs to.
face | A handle to the parent face object.
next | In some cases (like some font tools), several glyph slots per face object can be a good thing. As this is rare, the glyph slots are listed through a direct, single-linked list using its `next` field.
glyph_index | [Since 2.10] The glyph index passed as an argument to `FT_Load_Glyph` while initializing the glyph slot.
generic | A typeless pointer unused by the FreeType library or any of its drivers. It can be used by client applications to link their own data to each glyph slot object.
metrics | The metrics of the last loaded glyph in the slot. The returned values depend on the last load flags (see the `FT_Load_Glyph` API function) and can be expressed either in 26.6 fractional pixels or font units. Note that even when the glyph image is transformed, the metrics are not.
linearHoriAdvance | The advance width of the unhinted glyph. Its value is expressed in 16.16 fractional pixels, unless `FT_LOAD_LINEAR_DESIGN` is set when loading the glyph. This field can be important to perform correct WYSIWYG layout. Only relevant for scalable glyphs.
linearVertAdvance | The advance height of the unhinted glyph. Its value is expressed in 16.16 fractional pixels, unless `FT_LOAD_LINEAR_DESIGN` is set when loading the glyph. This field can be important to perform correct WYSIWYG layout. Only relevant for scalable glyphs.
advance | This shorthand is, depending on `FT_LOAD_IGNORE_TRANSFORM`, the transformed (hinted) advance width for the glyph, in 26.6 fractional pixel format. As specified with `FT_LOAD_VERTICAL_LAYOUT`, it uses either the `horiAdvance` or the `vertAdvance` value of `metrics` field.
format | This field indicates the format of the image contained in the glyph slot. Typically `FT_GLYPH_FORMAT_BITMAP`, `FT_GLYPH_FORMAT_OUTLINE`, or `FT_GLYPH_FORMAT_COMPOSITE`, but other values are possible.
bitmap | This field is used as a bitmap descriptor. Note that the address and content of the bitmap buffer can change between calls of `FT_Load_Glyph` and a few other functions.
bitmap_left | The bitmap's left bearing expressed in integer pixels.
bitmap_top | The bitmap's top bearing expressed in integer pixels. This is the distance from the baseline to the top-most glyph scanline, upwards y coordinates being positive.
outline | The outline descriptor for the current glyph image if its format is `FT_GLYPH_FORMAT_OUTLINE`. Once a glyph is loaded, `outline` can be transformed, distorted, emboldened, etc. However, it must not be freed. [Since 2.10.1] If `FT_LOAD_NO_SCALE` is set, outline coordinates of OpenType variation fonts for a selected instance are internally handled as 26.6 fractional font units but returned as (rounded) integers, as expected. To get unrounded font units, don't use `FT_LOAD_NO_SCALE` but load the glyph with `FT_LOAD_NO_HINTING` and scale it, using the font's `units_per_EM` value as the ppem.
num_subglyphs | The number of subglyphs in a composite glyph. This field is only valid for the composite glyph format that should normally only be loaded with the `FT_LOAD_NO_RECURSE` flag.
subglyphs | An array of subglyph descriptors for composite glyphs. There are `num_subglyphs` elements in there. Currently internal to FreeType.
control_data | Certain font drivers can also return the control data for a given glyph image (e.g. TrueType bytecode, Type 1 charstrings, etc.). This field is a pointer to such data; it is currently internal to FreeType.
control_len | This is the length in bytes of the control data. Currently internal to FreeType.
other | Reserved.
lsb_delta | The difference between hinted and unhinted left side bearing while auto-hinting is active. Zero otherwise.
rsb_delta | The difference between hinted and unhinted right side bearing while auto-hinting is active. Zero otherwise.

#### note

If `FT_Load_Glyph` is called with default flags (see `FT_LOAD_DEFAULT`) the glyph image is loaded in the glyph slot in its native format (e.g., an outline glyph for TrueType and Type 1 formats). [Since 2.9] The prospective bitmap metrics are calculated according to `FT_LOAD_TARGET_XXX` and other flags even for the outline glyph, even if `FT_LOAD_RENDER` is not set.

This image can later be converted into a bitmap by calling `FT_Render_Glyph`. This function searches the current renderer for the native image's format, then invokes it.

The renderer is in charge of transforming the native image through the slot's face transformation fields, then converting it into a bitmap that is returned in `slot->bitmap`.

Note that `slot->bitmap_left` and `slot->bitmap_top` are also used to specify the position of the bitmap relative to the current pen position (e.g., coordinates (0,0) on the baseline). Of course, `slot->format` is also changed to `FT_GLYPH_FORMAT_BITMAP`.

Here is a small pseudo code fragment that shows how to use `lsb_delta` and `rsb_delta` to do fractional positioning of glyphs:

      FT_GlyphSlot  slot     = face->glyph;
      FT_Pos        origin_x = 0;

      for all glyphs do
        <load glyph with `FT_Load_Glyph'>

        FT_Outline_Translate( slot->outline, origin_x & 63, 0 );

        <save glyph image, or render glyph, or ...>

        <compute kern between current and next glyph
         and add it to `origin_x'>

        origin_x += slot->advance.x;
        origin_x += slot->lsb_delta - slot->rsb_delta;
      endfor

Here is another small pseudo code fragment that shows how to use `lsb_delta` and `rsb_delta` to improve integer positioning of glyphs:

      FT_GlyphSlot  slot           = face->glyph;
      FT_Pos        origin_x       = 0;
      FT_Pos        prev_rsb_delta = 0;

      for all glyphs do
        <compute kern between current and previous glyph
         and add it to `origin_x'>

        <load glyph with `FT_Load_Glyph'>

        if ( prev_rsb_delta - slot->lsb_delta >  32 )
          origin_x -= 64;
        else if ( prev_rsb_delta - slot->lsb_delta < -31 )
          origin_x += 64;

        prev_rsb_delta = slot->rsb_delta;

        <save glyph image, or render glyph, or ...>

        origin_x += slot->advance.x;
      endfor

If you use strong auto-hinting, you must apply these delta values! Otherwise you will experience far too large inter-glyph spacing at small rendering sizes in most cases. Note that it doesn't harm to use the above code for other hinting modes also, since the delta values are zero then.

## FT_Glyph_Metrics

Defined in FT_FREETYPE_H (freetype/freetype.h).

      typedef struct  FT_Glyph_Metrics_
      {
        FT_Pos  width;
        FT_Pos  height;

        FT_Pos  horiBearingX;
        FT_Pos  horiBearingY;
        FT_Pos  horiAdvance;

        FT_Pos  vertBearingX;
        FT_Pos  vertBearingY;
        FT_Pos  vertAdvance;

      } FT_Glyph_Metrics;

A structure to model the metrics of a single glyph. The values are expressed in 26.6 fractional pixel format; if the flag `FT_LOAD_NO_SCALE` has been used while loading the glyph, values are expressed in font units instead.

#### fields

width | The glyph's width.
height | The glyph's height.
horiBearingX | Left side bearing for horizontal layout.
horiBearingY | Top side bearing for horizontal layout.
horiAdvance | Advance width for horizontal layout.
vertBearingX | Left side bearing for vertical layout.
vertBearingY | Top side bearing for vertical layout. Larger positive values mean further below the vertical glyph origin.
vertAdvance | Advance height for vertical layout. Positive values mean the glyph has a positive advance downward.

#### note

If not disabled with `FT_LOAD_NO_HINTING`, the values represent dimensions of the hinted glyph (in case hinting is applicable).

Stroking a glyph with an outside border does not increase `horiAdvance` or `vertAdvance`; you have to manually adjust these values to account for the added width and height.

FreeType doesn't use the ‘VORG’ table data for CFF fonts because it doesn't have an interface to quickly retrieve the glyph height. The y coordinate of the vertical origin can be simply computed as `vertBearingY + height` after loading a glyph.

## FT_Load_Glyph

Defined in FT_FREETYPE_H (freetype/freetype.h).

      FT_EXPORT( FT_Error )
      FT_Load_Glyph( FT_Face   face,
                     FT_UInt   glyph_index,
                     FT_Int32  load_flags );

Load a glyph into the glyph slot of a face object.

#### inout

face | A handle to the target face object where the glyph is loaded.

#### input

glyph_index | The index of the glyph in the font file. For CID-keyed fonts (either in PS or in CFF format) this argument specifies the CID value.
load_flags | A flag indicating what to load for this glyph. The `FT_LOAD_XXX` flags can be used to control the glyph loading process (e.g., whether the outline should be scaled, whether to load bitmaps or not, whether to hint the outline, etc).

#### return

FreeType error code. 0 means success.

#### note

For proper scaling and hinting, the active `FT_Size` object owned by the face has to be meaningfully initialized by calling `FT_Set_Char_Size` before this function, for example. The loaded glyph may be transformed. See `FT_Set_Transform` for the details.

For subsetted CID-keyed fonts, `FT_Err_Invalid_Argument` is returned for invalid CID values (that is, for CID values that don't have a corresponding glyph in the font). See the discussion of the `FT_FACE_FLAG_CID_KEYED` flag for more details.

If you receive `FT_Err_Glyph_Too_Big`, try getting the glyph outline at EM size, then scale it manually and fill it as a graphics operation.

## FT_LOAD_XXX

Defined in FT_FREETYPE_H (freetype/freetype.h).

    #define FT_LOAD_DEFAULT                      0x0
    #define FT_LOAD_NO_SCALE                     ( 1L << 0  )
    #define FT_LOAD_NO_HINTING                   ( 1L << 1  )
    #define FT_LOAD_RENDER                       ( 1L << 2  )
    #define FT_LOAD_NO_BITMAP                    ( 1L << 3  )
    #define FT_LOAD_VERTICAL_LAYOUT              ( 1L << 4  )
    #define FT_LOAD_FORCE_AUTOHINT               ( 1L << 5  )
    #define FT_LOAD_CROP_BITMAP                  ( 1L << 6  )
    #define FT_LOAD_PEDANTIC                     ( 1L << 7  )
    #define FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH  ( 1L << 9  )
    #define FT_LOAD_NO_RECURSE                   ( 1L << 10 )
    #define FT_LOAD_IGNORE_TRANSFORM             ( 1L << 11 )
    #define FT_LOAD_MONOCHROME                   ( 1L << 12 )
    #define FT_LOAD_LINEAR_DESIGN                ( 1L << 13 )
    #define FT_LOAD_SBITS_ONLY                   ( 1L << 14 )
    #define FT_LOAD_NO_AUTOHINT                  ( 1L << 15 )
      /* Bits 16-19 are used by `FT_LOAD_TARGET_` */
    #define FT_LOAD_COLOR                        ( 1L << 20 )
    #define FT_LOAD_COMPUTE_METRICS              ( 1L << 21 )
    #define FT_LOAD_BITMAP_METRICS_ONLY          ( 1L << 22 )
    #define FT_LOAD_NO_SVG                       ( 1L << 24 )

A list of bit field constants for `FT_Load_Glyph` to indicate what kind of operations to perform during glyph loading.

#### values

FT_LOAD_DEFAULT | Corresponding to 0, this value is used as the default glyph load operation. In this case, the following happens: FreeType looks for a bitmap for the glyph corresponding to the face's current size. If one is found, the function returns. The bitmap data can be accessed from the glyph slot (see note below). If no embedded bitmap is searched for or found, FreeType looks for a scalable outline. If one is found, it is loaded from the font file, scaled to device pixels, then ‘hinted’ to the pixel grid in order to optimize it. The outline data can be accessed from the glyph slot (see note below). Note that by default the glyph loader doesn't render outlines into bitmaps. The following flags are used to modify this default behaviour to more specific and useful cases.
FT_LOAD_NO_SCALE | Don't scale the loaded outline glyph but keep it in font units. This flag is also assumed if `FT_Size` owned by the face was not properly initialized. This flag implies `FT_LOAD_NO_HINTING` and `FT_LOAD_NO_BITMAP`, and unsets `FT_LOAD_RENDER`. If the font is ‘tricky’ (see `FT_FACE_FLAG_TRICKY` for more), using `FT_LOAD_NO_SCALE` usually yields meaningless outlines because the subglyphs must be scaled and positioned with hinting instructions. This can be solved by loading the font without `FT_LOAD_NO_SCALE` and setting the character size to `font->units_per_EM`.
FT_LOAD_NO_HINTING | Disable hinting. This generally generates ‘blurrier’ bitmap glyphs when the glyphs are rendered in any of the anti-aliased modes. See also the note below. This flag is implied by `FT_LOAD_NO_SCALE`.
FT_LOAD_RENDER | Call `FT_Render_Glyph` after the glyph is loaded. By default, the glyph is rendered in `FT_RENDER_MODE_NORMAL` mode. This can be overridden by `FT_LOAD_TARGET_XXX` or `FT_LOAD_MONOCHROME`. This flag is unset by `FT_LOAD_NO_SCALE`.
FT_LOAD_NO_BITMAP | Ignore bitmap strikes when loading. Bitmap-only fonts ignore this flag. `FT_LOAD_NO_SCALE` always sets this flag.
FT_LOAD_SBITS_ONLY | [Since 2.12] This is the opposite of `FT_LOAD_NO_BITMAP`, more or less: `FT_Load_Glyph` returns `FT_Err_Invalid_Argument` if the face contains a bitmap strike for the given size (or the strike selected by `FT_Select_Size`) but there is no glyph in the strike. Note that this load flag was part of FreeType since version 2.0.6 but previously tagged as internal.
FT_LOAD_VERTICAL_LAYOUT | Load the glyph for vertical text layout. In particular, the `advance` value in the `FT_GlyphSlotRec` structure is set to the `vertAdvance` value of the `metrics` field. In case `FT_HAS_VERTICAL` doesn't return true, you shouldn't use this flag currently. Reason is that in this case vertical metrics get synthesized, and those values are not always consistent across various font formats.
FT_LOAD_FORCE_AUTOHINT | Prefer the auto-hinter over the font's native hinter. See also the note below.
FT_LOAD_PEDANTIC | Make the font driver perform pedantic verifications during glyph loading and hinting. This is mostly used to detect broken glyphs in fonts. By default, FreeType tries to handle broken fonts also. In particular, errors from the TrueType bytecode engine are not passed to the application if this flag is not set; this might result in partially hinted or distorted glyphs in case a glyph's bytecode is buggy.
FT_LOAD_NO_RECURSE | Don't load composite glyphs recursively. Instead, the font driver fills the `num_subglyph` and `subglyphs` values of the glyph slot; it also sets `glyph->format` to `FT_GLYPH_FORMAT_COMPOSITE`. The description of subglyphs can then be accessed with `FT_Get_SubGlyph_Info`. Don't use this flag for retrieving metrics information since some font drivers only return rudimentary data. This flag implies `FT_LOAD_NO_SCALE` and `FT_LOAD_IGNORE_TRANSFORM`.
FT_LOAD_IGNORE_TRANSFORM | Ignore the transform matrix set by `FT_Set_Transform`.
FT_LOAD_MONOCHROME | This flag is used with `FT_LOAD_RENDER` to indicate that you want to render an outline glyph to a 1-bit monochrome bitmap glyph, with 8 pixels packed into each byte of the bitmap data. Note that this has no effect on the hinting algorithm used. You should rather use `FT_LOAD_TARGET_MONO` so that the monochrome-optimized hinting algorithm is used.
FT_LOAD_LINEAR_DESIGN | Keep `linearHoriAdvance` and `linearVertAdvance` fields of `FT_GlyphSlotRec` in font units. See `FT_GlyphSlotRec` for details.
FT_LOAD_NO_AUTOHINT | Disable the auto-hinter. See also the note below.
FT_LOAD_COLOR | Load colored glyphs. FreeType searches in the following order; there are slight differences depending on the font format. [Since 2.5] Load embedded color bitmap images (provided `FT_LOAD_NO_BITMAP` is not set). The resulting color bitmaps, if available, have the `FT_PIXEL_MODE_BGRA` format, with pre-multiplied color channels. If the flag is not set and color bitmaps are found, they are converted to 256-level gray bitmaps, using the `FT_PIXEL_MODE_GRAY` format. [Since 2.12] If the glyph index maps to an entry in the face's ‘SVG ’ table, load the associated SVG document from this table and set the `format` field of `FT_GlyphSlotRec` to `FT_GLYPH_FORMAT_SVG` ([since 2.13.1] provided `FT_LOAD_NO_SVG` is not set). Note that FreeType itself can't render SVG documents; however, the library provides hooks to seamlessly integrate an external renderer. See sections ‘The SVG driver’ and ‘OpenType SVG Fonts’ for more. [Since 2.10, experimental] If the glyph index maps to an entry in the face's ‘COLR’ table with a ‘CPAL’ palette table (as defined in the OpenType specification), make `FT_Render_Glyph` provide a default blending of the color glyph layers associated with the glyph index, using the same bitmap format as embedded color bitmap images. This is mainly for convenience and works only for glyphs in ‘COLR’ v0 tables (or glyphs in ‘COLR’ v1 tables that exclusively use v0 features). For full control of color layers use `FT_Get_Color_Glyph_Layer` and FreeType's color functions like `FT_Palette_Select` instead of setting `FT_LOAD_COLOR` for rendering so that the client application can handle blending by itself.
FT_LOAD_NO_SVG | [Since 2.13.1] Ignore SVG glyph data when loading.
FT_LOAD_COMPUTE_METRICS | [Since 2.6.1] Compute glyph metrics from the glyph data, without the use of bundled metrics tables (for example, the ‘hdmx’ table in TrueType fonts). This flag is mainly used by font validating or font editing applications, which need to ignore, verify, or edit those tables. Currently, this flag is only implemented for TrueType fonts.
FT_LOAD_BITMAP_METRICS_ONLY | [Since 2.7.1] Request loading of the metrics and bitmap image information of a (possibly embedded) bitmap glyph without allocating or copying the bitmap image data itself. No effect if the target glyph is not a bitmap image. This flag unsets `FT_LOAD_RENDER`.
FT_LOAD_CROP_BITMAP | Ignored. Deprecated.
FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH | Ignored. Deprecated.

#### note

By default, hinting is enabled and the font's native hinter (see `FT_FACE_FLAG_HINTER`) is preferred over the auto-hinter. You can disable hinting by setting `FT_LOAD_NO_HINTING` or change the precedence by setting `FT_LOAD_FORCE_AUTOHINT`. You can also set `FT_LOAD_NO_AUTOHINT` in case you don't want the auto-hinter to be used at all.

See the description of `FT_FACE_FLAG_TRICKY` for a special exception (affecting only a handful of Asian fonts).

Besides deciding which hinter to use, you can also decide which hinting algorithm to use. See `FT_LOAD_TARGET_XXX` for details.

Note that the auto-hinter needs a valid Unicode cmap (either a native one or synthesized by FreeType) for producing correct results. If a font provides an incorrect mapping (for example, assigning the character code U+005A, LATIN CAPITAL LETTER Z, to a glyph depicting a mathematical integral sign), the auto-hinter might produce useless results.

## FT_LOAD_TARGET_MODE

Defined in FT_FREETYPE_H (freetype/freetype.h).

    #define FT_LOAD_TARGET_MODE( x )                               \
              FT_STATIC_CAST( FT_Render_Mode, ( (x) >> 16 ) & 15 )

Return the `FT_Render_Mode` corresponding to a given `FT_LOAD_TARGET_XXX` value.

## FT_LOAD_TARGET_XXX

Defined in FT_FREETYPE_H (freetype/freetype.h).

    #define FT_LOAD_TARGET_( x )   ( FT_STATIC_CAST( FT_Int32, (x) & 15 ) << 16 )

    #define FT_LOAD_TARGET_NORMAL  FT_LOAD_TARGET_( FT_RENDER_MODE_NORMAL )
    #define FT_LOAD_TARGET_LIGHT   FT_LOAD_TARGET_( FT_RENDER_MODE_LIGHT  )
    #define FT_LOAD_TARGET_MONO    FT_LOAD_TARGET_( FT_RENDER_MODE_MONO   )
    #define FT_LOAD_TARGET_LCD     FT_LOAD_TARGET_( FT_RENDER_MODE_LCD    )
    #define FT_LOAD_TARGET_LCD_V   FT_LOAD_TARGET_( FT_RENDER_MODE_LCD_V  )

A list of values to select a specific hinting algorithm for the hinter. You should OR one of these values to your `load_flags` when calling `FT_Load_Glyph`.

Note that a font's native hinters may ignore the hinting algorithm you have specified (e.g., the TrueType bytecode interpreter). You can set `FT_LOAD_FORCE_AUTOHINT` to ensure that the auto-hinter is used.

#### values

FT_LOAD_TARGET_NORMAL | The default hinting algorithm, optimized for standard gray-level rendering. For monochrome output, use `FT_LOAD_TARGET_MONO` instead.
FT_LOAD_TARGET_LIGHT | A lighter hinting algorithm for gray-level modes. Many generated glyphs are fuzzier but better resemble their original shape. This is achieved by snapping glyphs to the pixel grid only vertically (Y-axis), as is done by FreeType's new CFF engine or Microsoft's ClearType font renderer. This preserves inter-glyph spacing in horizontal text. The snapping is done either by the native font driver, if the driver itself and the font support it, or by the auto-hinter. Advance widths are rounded to integer values; however, using the `lsb_delta` and `rsb_delta` fields of `FT_GlyphSlotRec`, it is possible to get fractional advance widths for subpixel positioning (which is recommended to use). If configuration option `AF_CONFIG_OPTION_TT_SIZE_METRICS` is active, TrueType-like metrics are used to make this mode behave similarly as in unpatched FreeType versions between 2.4.6 and 2.7.1 (inclusive).
FT_LOAD_TARGET_MONO | Strong hinting algorithm that should only be used for monochrome output. The result is probably unpleasant if the glyph is rendered in non-monochrome modes. Note that for outline fonts only the TrueType font driver has proper monochrome hinting support, provided the TTFs contain hints for B/W rendering (which most fonts no longer provide). If these conditions are not met it is very likely that you get ugly results at smaller sizes.
FT_LOAD_TARGET_LCD | A variant of `FT_LOAD_TARGET_LIGHT` optimized for horizontally decimated LCD displays.
FT_LOAD_TARGET_LCD_V | A variant of `FT_LOAD_TARGET_NORMAL` optimized for vertically decimated LCD displays.

#### note

You should use only one of the `FT_LOAD_TARGET_XXX` values in your `load_flags`. They can't be ORed.

If `FT_LOAD_RENDER` is also set, the glyph is rendered in the corresponding mode (i.e., the mode that matches the used algorithm best). An exception is `FT_LOAD_TARGET_MONO` since it implies `FT_LOAD_MONOCHROME`.

You can use a hinting algorithm that doesn't correspond to the same rendering mode. As an example, it is possible to use the ‘light’ hinting algorithm and have the results rendered in horizontal LCD pixel mode, with code like

      FT_Load_Glyph( face, glyph_index,
                     load_flags | FT_LOAD_TARGET_LIGHT );

      FT_Render_Glyph( face->glyph, FT_RENDER_MODE_LCD );

In general, you should stick with one rendering mode. For example, switching between `FT_LOAD_TARGET_NORMAL` and `FT_LOAD_TARGET_MONO` enforces a lot of recomputation for TrueType fonts, which is slow. Another reason is caching: Selecting a different mode usually causes changes in both the outlines and the rasterized bitmaps; it is thus necessary to empty the cache after a mode switch to avoid false hits.

## FT_Render_Glyph

Defined in FT_FREETYPE_H (freetype/freetype.h).

      FT_EXPORT( FT_Error )
      FT_Render_Glyph( FT_GlyphSlot    slot,
                       FT_Render_Mode  render_mode );

Convert a given glyph image to a bitmap. It does so by inspecting the glyph image format, finding the relevant renderer, and invoking it.

#### inout

slot | A handle to the glyph slot containing the image to convert.

#### input

render_mode | The render mode used to render the glyph image into a bitmap. See `FT_Render_Mode` for a list of possible values. If `FT_RENDER_MODE_NORMAL` is used, a previous call of `FT_Load_Glyph` with flag `FT_LOAD_COLOR` makes `FT_Render_Glyph` provide a default blending of colored glyph layers associated with the current glyph slot (provided the font contains such layers) instead of rendering the glyph slot's outline. This is an experimental feature; see `FT_LOAD_COLOR` for more information.

#### return

FreeType error code. 0 means success.

#### note

When FreeType outputs a bitmap of a glyph, it really outputs an alpha coverage map. If a pixel is completely covered by a filled-in outline, the bitmap contains 0xFF at that pixel, meaning that 0xFF/0xFF fraction of that pixel is covered, meaning the pixel is 100% black (or 0% bright). If a pixel is only 50% covered (value 0x80), the pixel is made 50% black (50% bright or a middle shade of grey). 0% covered means 0% black (100% bright or white).

On high-DPI screens like on smartphones and tablets, the pixels are so small that their chance of being completely covered and therefore completely black are fairly good. On the low-DPI screens, however, the situation is different. The pixels are too large for most of the details of a glyph and shades of gray are the norm rather than the exception.

This is relevant because all our screens have a second problem: they are not linear. 1 + 1 is not 2. Twice the value does not result in twice the brightness. When a pixel is only 50% covered, the coverage map says 50% black, and this translates to a pixel value of 128 when you use 8 bits per channel (0-255). However, this does not translate to 50% brightness for that pixel on our sRGB and gamma 2.2 screens. Due to their non-linearity, they dwell longer in the darks and only a pixel value of about 186 results in 50% brightness – 128 ends up too dark on both bright and dark backgrounds. The net result is that dark text looks burnt-out, pixely and blotchy on bright background, bright text too frail on dark backgrounds, and colored text on colored background (for example, red on green) seems to have dark halos or ‘dirt’ around it. The situation is especially ugly for diagonal stems like in ‘w’ glyph shapes where the quality of FreeType's anti-aliasing depends on the correct display of grays. On high-DPI screens where smaller, fully black pixels reign supreme, this doesn't matter, but on our low-DPI screens with all the gray shades, it does. 0% and 100% brightness are the same things in linear and non-linear space, just all the shades in-between aren't.

The blending function for placing text over a background is

      dst = alpha * src + (1 - alpha) * dst    ,

which is known as the OVER operator.

To correctly composite an anti-aliased pixel of a glyph onto a surface,

1. take the foreground and background colors (e.g., in sRGB space) and apply gamma to get them in a linear space,

2. use OVER to blend the two linear colors using the glyph pixel as the alpha value (remember, the glyph bitmap is an alpha coverage bitmap), and

3. apply inverse gamma to the blended pixel and write it back to the image.

Internal testing at Adobe found that a target inverse gamma of 1.8 for step 3 gives good results across a wide range of displays with an sRGB gamma curve or a similar one.

This process can cost performance. There is an approximation that does not need to know about the background color; see https://bel.fi/alankila/lcd/ and https://bel.fi/alankila/lcd/alpcor.html for details.

ATTENTION: Linear blending is even more important when dealing with subpixel-rendered glyphs to prevent color-fringing! A subpixel-rendered glyph must first be filtered with a filter that gives equal weight to the three color primaries and does not exceed a sum of 0x100, see section ‘Subpixel Rendering’. Then the only difference to gray linear blending is that subpixel-rendered linear blending is done 3 times per pixel: red foreground subpixel to red background subpixel and so on for green and blue.

## FT_Render_Mode

Defined in FT_FREETYPE_H (freetype/freetype.h).

      typedef enum  FT_Render_Mode_
      {
        FT_RENDER_MODE_NORMAL = 0,
        FT_RENDER_MODE_LIGHT,
        FT_RENDER_MODE_MONO,
        FT_RENDER_MODE_LCD,
        FT_RENDER_MODE_LCD_V,
        FT_RENDER_MODE_SDF,

        FT_RENDER_MODE_MAX

      } FT_Render_Mode;

      /* these constants are deprecated; use the corresponding */
      /* `FT_Render_Mode` values instead                       */
    #define ft_render_mode_normal  FT_RENDER_MODE_NORMAL
    #define ft_render_mode_mono    FT_RENDER_MODE_MONO

Render modes supported by FreeType 2. Each mode corresponds to a specific type of scanline conversion performed on the outline.

For bitmap fonts and embedded bitmaps the `bitmap->pixel_mode` field in the `FT_GlyphSlotRec` structure gives the format of the returned bitmap.

All modes except `FT_RENDER_MODE_MONO` use 256 levels of opacity, indicating pixel coverage. Use linear alpha blending and gamma correction to correctly render non-monochrome glyph bitmaps onto a surface; see `FT_Render_Glyph`.

The `FT_RENDER_MODE_SDF` is a special render mode that uses up to 256 distance values, indicating the signed distance from the grid position to the nearest outline.

#### values

FT_RENDER_MODE_NORMAL | Default render mode; it corresponds to 8-bit anti-aliased bitmaps.
FT_RENDER_MODE_LIGHT | This is equivalent to `FT_RENDER_MODE_NORMAL`. It is only defined as a separate value because render modes are also used indirectly to define hinting algorithm selectors. See `FT_LOAD_TARGET_XXX` for details.
FT_RENDER_MODE_MONO | This mode corresponds to 1-bit bitmaps (with 2 levels of opacity).
FT_RENDER_MODE_LCD | This mode corresponds to horizontal RGB and BGR subpixel displays like LCD screens. It produces 8-bit bitmaps that are 3 times the width of the original glyph outline in pixels, and which use the `FT_PIXEL_MODE_LCD` mode.
FT_RENDER_MODE_LCD_V | This mode corresponds to vertical RGB and BGR subpixel displays (like PDA screens, rotated LCD displays, etc.). It produces 8-bit bitmaps that are 3 times the height of the original glyph outline in pixels and use the `FT_PIXEL_MODE_LCD_V` mode.
FT_RENDER_MODE_SDF | This mode corresponds to 8-bit, single-channel signed distance field (SDF) bitmaps. Each pixel in the SDF grid is the value from the pixel's position to the nearest glyph's outline. The distances are calculated from the center of the pixel and are positive if they are filled by the outline (i.e., inside the outline) and negative otherwise. Check the note below on how to convert the output values to usable data.

#### note

The selected render mode only affects vector glyphs of a font. Embedded bitmaps often have a different pixel mode like `FT_PIXEL_MODE_MONO`. You can use `FT_Bitmap_Convert` to transform them into 8-bit pixmaps.

For `FT_RENDER_MODE_SDF` the output bitmap buffer contains normalized distances that are packed into unsigned 8-bit values. To get pixel values in floating point representation use the following pseudo-C code for the conversion.

    // Load glyph and render using FT_RENDER_MODE_SDF,
    // then use the output buffer as follows.

    ...
    FT_Byte  buffer = glyph->bitmap->buffer;

    for pixel in buffer
    {
      // `sd` is the signed distance and `spread` is the current spread;
      // the default spread is 2 and can be changed.

      float  sd = (float)pixel - 128.0f;

      // Convert to pixel values.
      sd = ( sd / 128.0f ) * spread;

      // Store `sd` in a buffer or use as required.
    }

FreeType has two rasterizers for generating SDF, namely:

1. `sdf` for generating SDF directly from glyph's outline, and

2. `bsdf` for generating SDF from rasterized bitmaps.

Depending on the glyph type (i.e., outline or bitmap), one of the two rasterizers is chosen at runtime and used for generating SDFs. To force the use of `bsdf` you should render the glyph with any of the FreeType's other rendering modes (e.g., `FT_RENDER_MODE_NORMAL`) and then re-render with `FT_RENDER_MODE_SDF`.

There are some issues with stability and possible failures of the SDF renderers (specifically `sdf`).

1. The `sdf` rasterizer is sensitive to really small features (e.g., sharp turns that are less than 1 pixel) and imperfections in the glyph's outline, causing artifacts in the final output.

2. The `sdf` rasterizer has limited support for handling intersecting contours and cannot handle self-intersecting contours whatsoever. Self-intersection happens when a single connected contour intersects itself at some point; having these in your font definitely poses a problem to the rasterizer and cause artifacts, too.

3. Generating SDF for really small glyphs may result in undesirable output; the pixel grid (which stores distance information) becomes too coarse.

4. Since the output buffer is normalized, precision at smaller spreads is greater than precision at larger spread values because the output range of [0..255] gets mapped to a smaller SDF range. A spread of 2 should be sufficient in most cases.

Points (1) and (2) can be avoided by using the `bsdf` rasterizer, which is more stable than the `sdf` rasterizer in general.

## FT_Get_Kerning

Defined in FT_FREETYPE_H (freetype/freetype.h).

      FT_EXPORT( FT_Error )
      FT_Get_Kerning( FT_Face     face,
                      FT_UInt     left_glyph,
                      FT_UInt     right_glyph,
                      FT_UInt     kern_mode,
                      FT_Vector  *akerning );

Return the kerning vector between two glyphs of the same face.

#### input

face | A handle to a source face object.
left_glyph | The index of the left glyph in the kern pair.
right_glyph | The index of the right glyph in the kern pair.
kern_mode | See `FT_Kerning_Mode` for more information. Determines the scale and dimension of the returned kerning vector.

#### output

akerning | The kerning vector. This is either in font units, fractional pixels (26.6 format), or pixels for scalable formats, and in pixels for fixed-sizes formats.

#### return

FreeType error code. 0 means success.

#### note

Only horizontal layouts (left-to-right & right-to-left) are supported by this method. Other layouts, or more sophisticated kernings, are out of the scope of this API function – they can be implemented through format-specific interfaces.

Kerning for OpenType fonts implemented in a ‘GPOS’ table is not supported; use `FT_HAS_KERNING` to find out whether a font has data that can be extracted with `FT_Get_Kerning`.

## FT_Kerning_Mode

Defined in FT_FREETYPE_H (freetype/freetype.h).

      typedef enum  FT_Kerning_Mode_
      {
        FT_KERNING_DEFAULT = 0,
        FT_KERNING_UNFITTED,
        FT_KERNING_UNSCALED

      } FT_Kerning_Mode;

      /* these constants are deprecated; use the corresponding */
      /* `FT_Kerning_Mode` values instead                      */
    #define ft_kerning_default   FT_KERNING_DEFAULT
    #define ft_kerning_unfitted  FT_KERNING_UNFITTED
    #define ft_kerning_unscaled  FT_KERNING_UNSCALED

An enumeration to specify the format of kerning values returned by `FT_Get_Kerning`.

#### values

FT_KERNING_DEFAULT | Return grid-fitted kerning distances in 26.6 fractional pixels.
FT_KERNING_UNFITTED | Return un-grid-fitted kerning distances in 26.6 fractional pixels.
FT_KERNING_UNSCALED | Return the kerning vector in original font units.

#### note

`FT_KERNING_DEFAULT` returns full pixel values; it also makes FreeType heuristically scale down kerning distances at small ppem values so that they don't become too big.

Both `FT_KERNING_DEFAULT` and `FT_KERNING_UNFITTED` use the current horizontal scaling factor (as set e.g. with `FT_Set_Char_Size`) to convert font units to pixels.

## FT_Get_Track_Kerning

Defined in FT_FREETYPE_H (freetype/freetype.h).

      FT_EXPORT( FT_Error )
      FT_Get_Track_Kerning( FT_Face    face,
                            FT_Fixed   point_size,
                            FT_Int     degree,
                            FT_Fixed*  akerning );

Return the track kerning for a given face object at a given size.

#### input

face | A handle to a source face object.
point_size | The point size in 16.16 fractional points.
degree | The degree of tightness. Increasingly negative values represent tighter track kerning, while increasingly positive values represent looser track kerning. Value zero means no track kerning.

#### output

akerning | The kerning in 16.16 fractional points, to be uniformly applied between all glyphs.

#### return

FreeType error code. 0 means success.

#### note

Currently, only the Type 1 font driver supports track kerning, using data from AFM files (if attached with `FT_Attach_File` or `FT_Attach_Stream`).

Only very few AFM files come with track kerning data; please refer to Adobe's AFM specification for more details.