Glyphs
editMap characters to glyphs
A font draws glyphs, not characters. MapCodePoint gives the glyph of a character from the character map of the font, or 0, the missing glyph. MapVariation gives the glyph of a variation sequence, a character followed by a variation selector.
Mapping characters one by one is enough for simple scripts and monospaced text. For most text, shape it instead: the font can replace, merge and move glyphs, which the character map does not say. See Shaping.
Read the metrics
The metrics are in font units: divide them by UnitsPerEm and multiply them by the size of the text.
| Metrics | Members of FontFace |
|---|---|
| Lines | GetLineMetrics, HorizontalAscender, HorizontalDescender, HorizontalLineGap, TypoAscender, TypoDescender, TypoLineGap, UseTypoMetrics, WinAscent, WinDescent |
| Letters | CapHeight, XHeight, AverageCharWidth |
| Decorations | UnderlinePosition, UnderlineThickness, StrikeoutPosition, StrikeoutSize, SubscriptYOffset, SuperscriptYOffset |
| Style | Weight, WidthClass, IsItalic, ItalicAngle, IsMonospaced |
| Glyphs | GetAdvanceWidth, GetLeftSideBearing, GetAdvanceHeight, GetTopSideBearing, GetVerticalOrigin, TryGetGlyphBounds |
| Vertical text | HasVerticalMetrics, VerticalAscender, VerticalDescender, VerticalLineGap |
| Baselines | TryGetBaseline, TryGetIdeographicCenter |
| Names | FamilyName, SubfamilyName, PostScriptName, GetName, GetNames |
GetLineMetrics gives the ascender, the descender and the line gap of a line of text from the table the font designates: the typographic metrics of OS/2 when UseTypoMetrics is set, else the metrics of hhea, else the typographic metrics, else the Windows metrics. Use it to measure and place lines the way the renderers of the framework do.
TableTags lists the tables of the font, and TryGetTable gives the bytes of any table, to read what the API does not expose.
Decode an outline
DecodeOutline sends the outline of a glyph to an OutlineSink: a sequence of contours made of lines and quadratic or cubic curves, in font units, with the y axis going up. Write a sink for your renderer. This one writes the data of an SVG path:
// Writes an outline as the data of an SVG path, in font units. The y axis of a font goes up, the one of SVG down.
private sealed class SvgPathSink : OutlineSink
{
private readonly StringBuilder _path = new();
public override void MoveTo(double x, double y) => Append('M', x, y);
public override void LineTo(double x, double y) => Append('L', x, y);
public override void QuadraticTo(double controlX, double controlY, double x, double y) => Append('Q', controlX, controlY, x, y);
public override void CubicTo(double control1X, double control1Y, double control2X, double control2Y, double x, double y) => Append('C', control1X, control1Y, control2X, control2Y, x, y);
public override void Close() => _path.Append('Z');
public override string ToString() => _path.ToString();
private void Append(char command, params ReadOnlySpan<double> coordinates)
{
_path.Append(command);
for (var i = 0; i < coordinates.Length; i += 2)
{
_path.Append(CultureInfo.InvariantCulture, $"{(i > 0 ? " " : "")}{coordinates[i]} {0 - coordinates[i + 1]}");
}
}
}static (string Path, GlyphBox Bounds) GetOutline(FontFace face, char character)
{
var glyph = face.MapCodePoint(character);
// The working storage of the outline, rented from the environment of the font, and the budget of the glyph
using var scratch = new GlyphScratch(face.Data.Environment.CreateAllocator("outline"));
var budget = new GlyphBudget(face.Data.Limits);
var sink = new SvgPathSink();
face.DecodeOutline(glyph, sink, scratch, ref budget);
face.TryGetGlyphBounds(glyph, scratch, out var bounds); // false for a glyph without outline, such as a space
return (sink.ToString(), bounds);
}For the letter l of Noto Sans, the path is M173 0L85 0L85 -760L173 -760L173 0Z, and the bounds go from (85, 0) to (173, 760).
- A GlyphScratch is the working storage of the outlines, rented from an allocator of the environment. Keep one per thread and reuse it: decoding the same glyphs again allocates nothing. Dispose it to return its storage.
- A GlyphBudget counts the work of one glyph against MaxGlyphComplexity: create one per glyph.
- A glyph without outline, such as a space, emits nothing.
- GlyphBoundsSink is a sink that measures an outline: the smallest rectangle that contains its points and the control points of its curves.
- The DecodeOutline overload that takes a size uses the bitmaps of one bit per pixel of the font (
EBDT,bdat): a rectangle per run of pixels of a row. A font loaded withuseEmbeddedBitmapsuses the strike made for exactly that size; a font without outlines uses the strike that suits any size (see Bitmap glyphs).
Hint outlines
At small sizes, an outline scaled exactly puts its edges across pixels. GlyphHinter decodes outlines fitted to the pixel grid of a size:
GlyphHinting.Light aligns the outlines along the vertical axis, without the instructions of the font, for any outline format.
GlyphHinting.Full uses the hints of the font, and makes the advances whole pixels:
- TrueType outlines: the instructions of the font, along both axes. An instance of a variable font is hinted with its own outlines and control values (the
cvartable). Instructions that break a rule of the specification leave the glyph, or the font when they are in its programs, unhinted. - CFF and CFF2 outlines: the horizontal stem hints of each glyph (with the hint masks that replace them along the outline) and the alignment zones of the font (
BlueValues,OtherBlues,BlueScale,BlueShift,BlueFuzz), along the vertical axis. The edges of the stems in a zone go to the zone, the other stems are a whole number of pixels thick, and the overshoots of the zones are suppressed at small sizes. A glyph without stem hints is not changed.
Hinting gives the mode that is used: Light for TrueType outlines without instructions, or whose programs cannot be run.
- TrueType outlines: the instructions of the font, along both axes. An instance of a variable font is hinted with its own outlines and control values (the
GlyphHinter.Create prepares a font at a size, and DecodeOutline gives the hinted outline of a glyph and its advance in pixels. A hinter keeps the state of the programs of the font: use it for one operation at a time, and dispose it.
Color glyphs
Some fonts have glyphs with their own colors, such as emoji. HasColorGlyphs tells whether a font has some, and IsColorGlyph whether a glyph is one.
- BuildColorGlyph gives the display list of a glyph of a
COLRtable, with the colors of a palette: layers, paints, gradients and compositions to draw. PaletteCount, TryGetPaletteColor and GetPaletteType read the palettes of theCPALtable. - The glyphs of the
sbixandCBDTtables are images: see Bitmap glyphs. - TryGetSvgGlyph finds the SVG document that describes a glyph of an
SVGtable, and GetSvgDocument gives its text, expanded when the font compresses it with gzip. HasSvgGlyphs tells whether a font has such glyphs.
A document can describe several glyphs: the element of a glyph has the identifier glyph followed by the glyph identifier, and the glyph is drawn as a use element that refers to it would draw it, in font units with the y axis going down from the baseline. Drawing the document is up to you:
static string? GetSvgDocument(FontFace face, char character)
{
var glyph = face.MapCodePoint(character);
if (!face.TryGetSvgGlyph(glyph, out var svgGlyph))
return null; // no SVG description: the glyph is drawn from its outline, or from another color table
// The text of the document, expanded when the font compresses it. The document can describe several glyphs
// (FirstGlyphId to LastGlyphId): the element of this one has the identifier "glyph" + GlyphId.
return Encoding.UTF8.GetString(face.GetSvgDocument(svgGlyph).Span);
}A font that has a malformed list of documents is read without its SVG table: its glyphs are then outlines. A compressed document that is malformed throws an InvalidFontException when it is read.
To draw color glyphs without writing a renderer, use the text API of Meziantou.Framework.Imaging.
Bitmap glyphs
Some fonts give glyphs as images, in strikes made for a number of pixels per em: images in color (sbix, CBDT) and bitmaps without colors (EBDT, bdat in the fonts of Apple). A font can have no outlines at all: its Outlines is None, and IsBitmapOnly tells that its glyphs are bitmaps. Its metrics, character map and layout tables are read like those of any font; a font of Apple without outlines can have a bhed table instead of head.
- TryGetBitmapGlyph finds the image of a glyph a renderer draws as an image, in the strike that suits a size (the smallest one that is at least as large, else the largest one): the images of
sbixandCBDT, and the bitmaps of several bits per pixel ofEBDTwhen the font uses them. HasBitmapGlyphs tells whether a font has some. - TryGetAnyBitmapGlyph finds the image of a glyph in any of these tables, the bitmaps of one bit per pixel included.
- A BitmapGlyph gives the strike, the placement of the image and its format (BitmapGlyph.Format). The PNG, JPEG and TIFF images are encoded data in the font, at Offset: decoding them is up to you (Font.DecodeBitmapGlyph of Meziantou.Framework.Imaging does it).
- The pixels that are not encoded, Mask (a coverage of 1, 2, 4 or 8 bits, drawn with the color of the text) and Bgra (colors of 32 bits), are decoded by DecodeBitmap, with the glyphs a glyph is made of (image formats 8 and 9): an image of Width by Height pixels.
- ColorGlyph.FromImage and ColorGlyph.FromMask make the display list that draws a decoded image, in its colors or in the color of the text.