opentype

package module
v0.27.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: BSD-3-Clause Imports: 14 Imported by: 15 modules, 13 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-opentype/opentype

CI pkg.go.dev coverage go license

Pure-Go, CGO=0, standard-library-only parser, shaper and anti-aliased rasteriser for TrueType/OpenType fonts. No golang.org/x/*, no third-party modules — it imports only image, encoding/binary, math, errors and friends, so it builds for every Go target including GOOS=js GOARCH=wasm.

It exists to functionally replace the narrow slice of golang.org/x/image/font/opentype that a glyph-blitting UI needs — parse a font blob, build a face at a pixel size, pull per-rune advances and 8-bit alpha coverage masks — and then goes further: CFF/CFF2 outlines, variable fonts, GPOS/GSUB shaping, kerning and TrueType/CFF hinting are all in scope.

Install

go get github.com/go-opentype/opentype

Quick start

package main

import (
	"fmt"
	"os"

	"github.com/go-opentype/opentype"
)

func main() {
	ttf, err := os.ReadFile("MyFont.ttf") // or .otf (CFF/CFF2)
	if err != nil {
		panic(err)
	}

	f, err := opentype.Parse(ttf)
	if err != nil {
		panic(err)
	}
	face := f.NewFace(16) // 16px per em

	m := face.Metrics()             // Metrics{Ascent, Descent, Height} in pixels
	w := face.Measure("Hello")      // total advance width in pixels
	adv := face.Advance('H')        // one rune's advance in pixels
	fmt.Println(m, w, adv)

	// Rasterise a glyph with (penX, baselineY) as the pen origin on the baseline.
	bounds, mask, maskp, advance, ok := face.GlyphMask('H', 0, 16)
	if ok && mask != nil {
		// Composite the coverage mask onto your destination:
		// pixel (maskp.X+i, maskp.Y+j) covers destination (bounds.Min.X+i, bounds.Min.Y+j).
		_ = bounds
		_ = maskp
		_ = advance
	}
}

The GlyphMask shape deliberately mirrors x/image's font.Face.Glyph, so swapping this in for the x/image face is mechanical.

Features

  • sfnt container parsing (0x00010000 TrueType and OTTO CFF magics)
  • WOFF and WOFF2 web fonts unwrapped by Parse. WOFF2 is inflated with the decoder-only github.com/dsnet/compress/brotli, not github.com/andybalholm/brotli, whose root package imports net/http. Its init, and crypto/tls's behind it, used to be linked into every importer: 1.8 MB of a 7.5 MB GOOS=js program that only draws text. Inflation is bounded by the size the WOFF2 directory declares, at most 256 MiB, so a decompression bomb is refused. The trade-off is speed: dsnet inflates about 1.37× slower (≈0.4 ms more per 200 KB font, measured on one core at load 7–10). That is an open item.
  • TrueType glyf outlines — simple and composite glyphs, implied on-curve midpoint synthesis, cycle/depth-guarded composites
  • CFF and CFF2 outlines — Type 2 charstrings, subroutines, seac accent composition, CFF2 variable-font blend operators
  • Variable fonts — fvar axes and named instances, avar axis-value mapping, gvar/CFF2 glyph-outline interpolation, and HVAR/VVAR/MVAR metric variation, via (*Face).SetVariation
  • GSUB/GPOS shaping — ligatures, contextual and positional-form substitution (isol/init/medi/fina), pair/single/cursive positioning, mark-to-base and mark-to-mark attachment
  • Kerning — GPOS pair positioning with legacy kern-table fallback through a single Kerner
  • Hinting — TrueType instruction interpreter and a CFF/Type 2 stem grid-fitter, toggled per Face with SetHinting; optional SetStemDarkening
  • Vertical metrics — vhea/vmtx/VORG-aware vertical advances and origins for vertical writing modes
  • OpenType MATH table — math-typesetting metrics (constants, per-glyph italic correction / top-accent attachment / four-corner kerning, and stretchy-glyph size variants and assemblies), exposed pixel-scaled through a Face
  • Font descriptors — the OS/2- and head/post-derived scalars a PDF /FontDescriptor or CSS @font-face needs (Ascent, Descent, FontBBox, CapHeight, XHeight, ItalicAngle, WeightClass, WidthClass, StemV, Flags, IsFixedPitch/IsItalic/IsSerif)
  • Subsetting & instancing — SubsetTrueType/SubsetCFF cut a font down to a glyph set (closing composite/seac dependencies and remapping ids), and Instance/InstanceBytes bake a variable font to a static instance — the writer side needed to embed fonts in PDFs; the instance's OS/2 usWeightClass/fsSelection and head macStyle follow the wght/ital/ slnt coordinates it was baked at
  • Anti-aliased rasterisation via 4×4 supersampling under the non-zero winding rule

A Font is immutable after Parse and safe for concurrent use. A Face caches rasterised glyphs and is not safe for concurrent use; build one Face per goroutine if needed.

API tour

Symbol Purpose
Parse(b []byte) (*Font, error) Decode an sfnt (TrueType or CFF/OTTO) font blob.
(*Font).NumGlyphs() int Glyph count (from maxp).
(*Font).GlyphIndex(r rune) (GlyphIndex, bool) Map a rune via the cmap.
(*Font).GlyphIndexVariation(r, vs rune) (GlyphIndex, bool) Map a rune + Unicode variation selector.
(*Font).Axes() []Axis Variable-font design axes (fvar).
(*Font).NamedInstances() []NamedInstance Named positions in the variation space.
(*Font).GPOS() *GPOS / (*Font).GSUB() *GSUB Parsed layout tables, or nil.
(*Font).HasVerticalMetrics() bool Whether vhea/vmtx are present.
(*Font).NewFace(sizePx int) *Face Build a sized face (scale = sizePx / unitsPerEm).
(*Face).Metrics() Metrics Ascent, Descent, Height in pixels.
(*Face).Advance(r rune) int / (*Face).Measure(s string) int Rune / string advance in pixels.
(*Face).Kern(prev, r rune) int / (*Face).MeasureKerned(s string) int GPOS-or-kern pair adjustment.
(*Face).GlyphMask(r, x, y) (image.Rectangle, *image.Alpha, image.Point, int, bool) Rasterised glyph + advance.
(*Face).GlyphControlBox(g GlyphIndex) (xMin, yMin, xMax, yMax float64, ok bool) A glyph's control box in font units — every outline point, the cubics' control points included, unhinted: FreeType's FT_Glyph_Get_CBox(…, FT_GLYPH_BBOX_UNSCALED, …), exact. XeTeX takes an OpenType glyph's italic correction from it (max(0, xMax − advance)). GlyphOutline returns CFF outlines flattened, so their extent is the curve's, which can fall short of it.
(*Face).Shape(text string, features ...string) []GlyphIndex GSUB-substituted glyph run.
(*Face).ShapePositioned(text string, features ...string) []PositionedGlyph GSUB + GPOS glyph run with pen offsets.
(*Face).SetVariation(coords map[string]float64) Instance a variable font at the given axis coordinates.
(*Face).SetHinting(on bool) / (*Face).SetStemDarkening(on bool) Toggle the TrueType/CFF hinter.
(*Face).VerticalAdvance(r rune) int / (*Face).VerticalOrigin(r rune) (int, bool) Vertical writing-mode metrics.
(*Font).HasMath() bool Whether the font carries an OpenType MATH table.
(*Face).MathConstant(w MathConstant) int / (*Face).ItalicCorrection(g GlyphIndex) int / (*Face).MathVariants(g, vertical) ([]MathVariant, *MathAssembly) Pixel-scaled MATH-table metrics for a math-layout engine.
(*Font).Ascent/Descent/LineGap/FontBBox/CapHeight/XHeight/ItalicAngle/WeightClass/WidthClass/StemV/Flags/IsFixedPitch/IsItalic/IsSerif Font-descriptor scalars for PDF /FontDescriptor and CSS @font-face. Ascent/Descent/LineGap are hhea's.
(*Font).TypoAscent/TypoDescent/TypoLineGap/WinAscent/WinDescent/UseTypoMetrics OS/2's line metrics — the ones the spec recommends for new text-layout implementations, hhea's being platform-specific. TypoDescent is negative below the baseline, WinDescent positive; usWin* are a clipping extent, not line spacing.
(*Font).Instance(coords map[string]float64) (*Font, error) / (*Font).InstanceBytes(coords) ([]byte, error) Bake a variable font to a static instance (as a *Font or a new sfnt blob).
(*Font).SubsetTrueType(gids []GlyphIndex) ([]byte, map[GlyphIndex]GlyphIndex, error) Cut a TrueType font to a glyph set, closing composites and returning the old→new id map.
(*Font).SubsetCFF(gids []GlyphIndex) ([]byte, error) Cut a CFF/OTTO font to a glyph set (closing seac accents).

See example_test.go for runnable examples of each of these, and go doc github.com/go-opentype/opentype for the full reference.

Support matrix

  • sfnt container (0x00010000 and true TrueType magics, OTTO CFF magic)
  • head, maxp, hhea, hmtx (including the trailing-run shared advance)
  • cmap formats 0, 2, 4, 6, 8, 10, 12, 13 and 14 (Unicode variation sequences), preferring the richest available (12/13 over 4/6)
  • loca (short and long), glyf simple and composite TrueType glyphs
  • CFF and CFF2 (OTTO) Type 2 charstring outlines, including seac
  • fvar/avar/gvar/HVAR/VVAR/MVAR and CFF2 blends for variable fonts, plus Instance/InstanceBytes to bake a static instance
  • GSUB/GPOS/GDEF, the legacy kern table
  • OS/2 + head/post font-descriptor scalars (Ascent, Descent, FontBBox, CapHeight, XHeight, ItalicAngle, WeightClass, WidthClass, StemV, Flags, …) for PDF/CSS embedding
  • OS/2 typographic line metrics — TypoAscent, TypoDescent, TypoLineGap, WinAscent, WinDescent, UseTypoMetrics — which the OpenType spec names for new text-layout work, hhea's ascender/descender being Apple-specific. A layout engine should read the sTypo* set, honour USE_TYPO_METRICS, and leave usWin* for clipping regions
  • subsetting — SubsetTrueType (glyf, composite-closure aware, with an old→new id map) and SubsetCFF (seac-closure aware)
  • the OpenType MATH table — math-typesetting metrics (constants, per-glyph italic correction / top-accent attachment / corner kerning, and stretchy-glyph size variants and assemblies), exposed pixel-scaled through a Face (HasMath, MathConstant, ItalicCorrection, TopAccentAttachment, MathKern, MathVariants); math layout is left to a higher-level engine
  • TrueType instruction hinting and a CFF stem grid-fitter/darkener
  • vhea/vmtx/VORG vertical metrics
  • anti-aliased rasterisation via 4×4 supersampling under the non-zero winding rule

Rasterisation uses uniform supersampling (not the delta-hinted rasterisation of a native TrueType/CFF hinter's drop-out control), so it favours correctness and portability over the very last drop of small-size sharpness.

Untrusted fonts

Parse, ParseType1 and the glyph accessors may be fed fonts from anywhere. What a font declares is checked before it is allocated, so a few hundred bytes cannot ask for gigabytes (a Go out-of-memory cannot be recovered):

  • Declared counts. Every count that sizes an allocation is checked against the bytes actually present, by division, so a 32-bit count cannot overflow the check on a 32-bit build.
  • Shared and multiplied structure. A sub-table that many offsets point at is decoded once. Coverage and ClassDef tables are binary-searched in the font's bytes, as HarfBuzz does, never expanded glyph by glyph. A per-Parse budget of 1 MiB plus 64 bytes per input byte backs this up.
  • Per glyph. A composite TrueType glyph may expand to at most 65,535 points. A CFF, CFF2 or Type 1 charstring may execute at most 131,072 operators, subroutines included, and emit at most 65,536 points. The largest glyphs measured on several hundred real fonts stay 8.8 to 103 times below these limits.

Nothing bounds the work over a whole font, since each glyph may take up to its own limit; Face.GlyphCost (and GlyphOutlineCost, GlyphSVGPathCost, which return it with the outline from one interpretation) reports the operators or points a glyph took, so a caller sums them and refuses the font past a total of its own, deterministically and with no state shared on the Font. A glyph over its limit reports an error matching ErrOutlineBudget. STIX Two Math's 6,760 glyphs total 166,885 operators.

A font past any bound is refused with an error, never truncated. Every bound has a test that builds the hostile font and asserts the refusal under a small allocation ceiling, and each case is a committed fuzz seed.

Testing

Tests never depend on an external font to reach 100% coverage: they synthesise minimal-but-valid TrueType and CFF fonts in memory to deterministically exercise every parse, shape and raster branch, including the error paths. A real-world font, Adobe's Source Serif 4 (SIL Open Font License, bundled under testdata/), is used in example_test.go and in a handful of sanity-check tests, so the documented examples double as an end-to-end smoke test against production CFF charstrings and Private DICTs. CI enforces 100.0% statement coverage, go vet, and a cross-compile smoke over linux/{amd64,arm64,riscv64,loong64,ppc64le,s390x}, js/wasm, darwin/arm64 and windows/amd64.

Part of the go-opentype pure-Go text stack

go-opentype/opentype is the parsing/shaping/rasterising engine at the base of a dependency-free text stack:

  • opentype (this repo) — font parsing, GSUB/GPOS shaping, hinting and rasterisation.
  • bidi — a full Unicode Bidirectional Algorithm (UBA) implementation, for ordering mixed left-to-right/right-to-left text before it is shaped.
  • shape — a HarfBuzz-lite complex-script shaper (Arabic, Indic, Hangul, USE, Egyptian hieroglyphs, ...) built on this package's GSUB/GPOS engine.
  • fonts — 46 bundled OFL/BSD font families (Latin, non-Latin scripts and CJK), per-family lazily go:embed-ed, ready to feed to Parse.

License

BSD-3-Clause. See LICENSE.

Documentation

Overview

Package opentype is a pure-Go, CGO=0, standard-library-only parser and anti-aliased rasteriser for TrueType/OpenType fonts.

It is a functional replacement for the narrow slice of golang.org/x/image/font/opentype needed by a glyph-blitting UI: parse a font blob, build a Face at a pixel size, then obtain per-rune advances and 8-bit alpha coverage masks.

Scope

The sfnt container, head, maxp, hhea, hmtx, cmap (formats 4 and 12), loca and glyf tables, simple and composite glyphs, implied on-curve points, and a non-zero-winding supersampling rasteriser. Beyond that: CFF and CFF2 ('OTTO') Type 2 charstrings, variable fonts ('fvar'/'avar'/'gvar' and the CFF2 blends), GSUB/GPOS/GDEF shaping with the legacy 'kern' table as a fallback, and both hinters. See the README for the full support matrix, and Face.ShapePositionedUnits for the shaped-run entry point.

⛔⛔ THIS PARAGRAPH USED TO SAY THE OPPOSITE, AND A CONSUMER BELIEVED IT. It read "Phase 1 covers TrueType 'glyf' outlines … OpenType/CFF ('OTTO') outlines, GPOS/GSUB shaping, kerning and hinting are not implemented" long after each of those landed with its own tests — gsub.go, gpos.go, kern.go, shape.go, hint.go, cff.go, cff2.go, cffhint.go. The README's matrix said "done" at the same time, so the two halves of this repository's own documentation disagreed, and the stale half is the one a consumer reads first.

What that cost, measured in go-tex/engine at its origin/main: the engine calls Shape(text, "liga") for ligatures and then obtains kerning ONE RUNE PAIR AT A TIME through KernUnits(prev, cur) — ShapePositioned and ShapePositionedUnits are never called, so contextual GPOS, cursive attachment and mark attachment are not missing there but UNASKED FOR. The doc comment on ShapePositionedUnits describes that engine's predicament in its own words; this paragraph is why it had no reason to look.

doc_scope_test.go now fails if this paragraph calls a feature unimplemented while the file implementing it is in the tree.

The OpenType MATH table (math-typesetting metrics: constants, per-glyph italic correction and kerning, and stretchy-glyph size variants and assemblies) is decoded and exposed pixel-scaled through a Face; see Font.HasMath and math.go. Math layout itself (box building, the TeX math rules) is a higher-level engine that consumes these values.

Usage

f, err := opentype.Parse(ttf)
if err != nil { /* handle */ }
face := f.NewFace(16)
adv := face.Measure("Hello")
bounds, mask, maskp, advance, ok := face.GlyphMask('H', penX, baselineY)

A Font is immutable after Parse and safe for concurrent use; a Face caches rasterised glyphs and is not safe for concurrent use.

Embedding and subsetting

For a consumer that embeds a font (a PDF or EPUB writer), the package exposes the primitives such an embedder otherwise re-implements by re-parsing the sfnt: the PDF FontDescriptor scalars (Font.UnitsPerEm, Font.FontBBox, Font.CapHeight, Font.XHeight, Font.ItalicAngle, Font.StemV, Font.Flags, ...); raw table access (Font.TableTags, Font.Table); by-glyph-index advances that honour the current variation (Face.AdvanceIndex, Face.AdvanceIndexUnits, Face.VerticalAdvanceIndex); TrueType glyph subsetting (Font.SubsetTrueType) and CFF charstring subsetting (Font.SubsetCFF); and baking a variable font at a chosen axis position into a static instance (Font.Instance, Font.InstanceBytes).

Index

Examples

Constants

View Source
const SubpixelPhases = 4

SubpixelPhases is the number of horizontal positions within a pixel that Face.GlyphMaskIndexAt tells apart: a glyph origin is rounded to the nearest 1/SubpixelPhases of a pixel, an error of at most 1/(2*SubpixelPhases) px.

Variables

View Source
var ErrOutlineBudget = errors.New("glyph outline exceeds its per-glyph budget")

ErrOutlineBudget is what a glyph's refusal wraps when the glyph exceeds the per-glyph budget of its outline: more than 131,072 operators or 65,536 points in a CFF, CFF2 or Type 1 charstring, more than 65,535 points in a composite glyf glyph. Face.GlyphCost, Face.GlyphOutlineCost and Face.GlyphSVGPathCost report it; test for it with errors.Is.

Functions

This section is empty.

Types

type Axis added in v0.2.0

type Axis struct {
	Tag     string  // four-character axis tag, e.g. "wght", "wdth", "slnt"
	Min     float64 // minimum user coordinate
	Default float64 // default user coordinate (the font's default master)
	Max     float64 // maximum user coordinate
	Flags   uint16  // axis flags (bit 0: hidden axis)
	NameID  uint16  // 'name' table entry describing the axis
}

Axis is one design-variation axis of a variable font, decoded from the 'fvar' table. Min, Default and Max are user-space coordinates (for example 100, 400 and 900 for a typical weight axis).

type Face

type Face struct {
	// contains filtered or unexported fields
}

Face renders a Font at a fixed pixel size. It caches rasterised glyphs and is not safe for concurrent use; build one Face per goroutine if needed.

func (*Face) Advance

func (fc *Face) Advance(r rune) int

Advance returns the horizontal advance of r in WHOLE pixels, or 0 if the rune is not mapped by the font's cmap. When a variation is set the HVAR delta (or the gvar phantom-point fallback) is included.

⛔ IT ROUNDS, and at a text size that is coarse: a consumer laying out text wants AdvanceUnits. On STIXTwoMath at 10pt — where one pixel is one point — the space advance is 2.35 and this returns 2. A typesetter reading it puts every interword space 0.35pt narrow, which is ~3.9pt per 66-character line. go-tex did exactly that until it was measured.

func (*Face) AdvanceIndex added in v0.5.0

func (fc *Face) AdvanceIndex(gid GlyphIndex) int

AdvanceIndex returns the horizontal advance of glyph gid in whole pixels at the face's size, honouring the face's current variation (the HVAR delta, or the gvar phantom-point fallback, is folded in exactly as Face.Advance does for a rune). With no variation set it is the base advance scaled to pixels. It is the by-glyph-index counterpart of Face.Advance, for a caller that already holds a glyph id rather than a rune. An out-of-range gid advances by zero.

func (*Face) AdvanceIndexUnits added in v0.5.0

func (fc *Face) AdvanceIndexUnits(gid GlyphIndex) float64

AdvanceIndexUnits returns the horizontal advance of glyph gid in font units at the face's current variation, as a float64 (the value AdvanceIndex rounds and scales to pixels). It is the exact width a PDF /W array wants — font-unit widths that track the instanced font — without the caller re-deriving the HVAR delta. An out-of-range gid advances by zero.

func (*Face) AdvanceUnits added in v0.19.0

func (fc *Face) AdvanceUnits(r rune) float64

AdvanceUnits returns the horizontal advance of r in pixels WITHOUT rounding, or 0 if the rune is not mapped by the font's cmap.

It is Advance's exact counterpart, as AdvanceIndexUnits is AdvanceIndex's. A layout engine that accumulates advances must use this one: rounding each glyph to a whole pixel accumulates along the line, and the error does not cancel — it is a bias toward whatever side the font's widths happen to fall.

func (*Face) Font added in v0.3.1

func (fc *Face) Font() *Font

Font returns the Font this Face renders. It lets a shaper reach the font's layout tables (Font.GSUB, Font.GPOS) and per-glyph metrics (Font.GlyphAdvance) while keeping the Face for pixel sizing.

func (*Face) GlyphControlBox added in v0.24.0

func (fc *Face) GlyphControlBox(gid GlyphIndex) (xMin, yMin, xMax, yMax float64, ok bool)

GlyphControlBox returns glyph gid's control box in font design units, Y up: the bounds of all its outline points, the curves' control points included, unhinted and at the face's current variation. It is FreeType's FT_Glyph_Get_CBox with FT_GLYPH_BBOX_UNSCALED — the box XeTeX takes a glyph's italic correction from — and it can be wider than the ink, never narrower.

For the ink's own bounds use Face.GlyphOutline; CFF outlines come back flattened there, so their extent is the curves' and not their control points'.

ok is false when gid is out of range or its outline is corrupt. An empty glyph (a space) has a zero box and ok true, as FreeType gives it.

func (*Face) GlyphCost added in v0.25.0

func (fc *Face) GlyphCost(gid GlyphIndex) (cost int, err error)

GlyphCost is the work outlining glyph gid takes, so that a caller can bound a whole font deterministically: sum the costs of its glyphs and refuse the font past a total of its own. It is stateless: nothing is stored on the Font or the Face, and a cost is a property of the glyph, not of the order the glyphs were asked in.

The unit depends on the outline kind:

  • CFF, CFF2 and Type 1: the charstring operators executed, those of the subroutines it calls and of the seac components it composes included. Operands are not counted. A glyph is limited to 131,072 operators.
  • glyf (TrueType): the points the glyph expands to, a composite's components included, a contour counting at least one. A glyph is limited to 65,535 points. The TrueType instructions run when hinting is on are not counted; they have a budget of their own of 1,000,000 per glyph.

The units are not comparable across kinds; a caller bounds each kind by its own total.

Measured on the machine's fonts, the busiest glyph and the total over all glyphs: STIX Two Math (CFF, 6,760 glyphs): 1,267 operators for the busiest glyph, 166,885 in all (TestGlyphCostSTIXTwoMath), against the 131,072 one glyph may take. Over the 227 fonts of the development machine, STIX Two Math has the largest charstring total and its busiest glyph is the busiest of the charstring fonts; the glyf fonts reach 4,103 points for the busiest glyph (Kokonor) and 3,554,977 in all (Arial Unicode, 50,377 glyphs).

err is the refusal of a glyph that Face.GlyphOutline reports as not ok: it wraps ErrOutlineBudget when the glyph exceeds its budget, and is another error for a glyph out of range or corrupt. A valid but empty glyph costs 0.

func (*Face) GlyphMask

func (fc *Face) GlyphMask(r rune, x, y int) (bounds image.Rectangle, mask *image.Alpha, maskp image.Point, advance int, ok bool)

GlyphMask rasterises r and positions it with (x, y) as the pen origin on the baseline. It returns the destination bounds, an *image.Alpha coverage mask, the offset into that mask corresponding to bounds.Min (always the origin), the advance width in pixels, and ok.

ok is false when the rune is not mapped by the cmap or its glyph outline is corrupt; callers should render nothing in that case. A mapped-but-empty glyph (for example a space) returns ok true with a nil mask, an empty bounds, and its advance.

Example

ExampleFace_GlyphMask rasterises a single glyph and reports the coverage mask placement, exactly the shape golang.org/x/image/font.Face.Glyph returns, so swapping this Face in for an x/image face is mechanical.

package main

import (
	"fmt"
	"os"

	"github.com/go-opentype/opentype"
)

// loadTestFont reads the CFF/OpenType font bundled under testdata for the
// examples below (Adobe Source Serif 4, SIL Open Font License; see
// testdata/OFL.txt).
func loadTestFont() *opentype.Font {
	b, err := os.ReadFile("testdata/SourceSerif4-Regular.otf")
	if err != nil {
		panic(err)
	}
	f, err := opentype.Parse(b)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	f := loadTestFont()
	face := f.NewFace(16)

	bounds, mask, maskp, advance, ok := face.GlyphMask('H', 0, 16)
	fmt.Println("ok =", ok)
	fmt.Println("bounds =", bounds)
	fmt.Println("mask != nil:", mask != nil)
	if mask != nil {
		fmt.Println("mask bounds =", mask.Bounds())
	}
	fmt.Println("maskp =", maskp)
	fmt.Println("advance =", advance)
}
Output:
ok = true
bounds = (0,5)-(12,16)
mask != nil: true
mask bounds = (0,0)-(12,11)
maskp = (0,0)
advance = 13

func (*Face) GlyphMaskIndex added in v0.3.3

func (fc *Face) GlyphMaskIndex(gid GlyphIndex, x, y int) (bounds image.Rectangle, mask *image.Alpha, maskp image.Point, advance int, ok bool)

GlyphMaskIndex rasterises the glyph with index gid directly — bypassing the cmap — and positions it with (x, y) as the pen origin on the baseline. It is the by-glyph-index counterpart of Face.GlyphMask: a complex-text shaper (see github.com/go-opentype/shape) emits glyph indices after applying GSUB substitutions and GPOS positioning, so the runes have already been resolved to glyphs and a caller must render each glyph by its index rather than by a rune. Callers add the shaper's per-glyph pixel offset to (x, y) before the call and advance the pen by the shaper's advance afterwards.

It returns the destination bounds, an *image.Alpha coverage mask, the offset into that mask corresponding to bounds.Min (always the origin), the glyph's own horizontal advance width in pixels, and ok.

ok is false when gid is out of range or its outline is corrupt; callers should render nothing in that case. A valid-but-empty glyph (for example a space) returns ok true with a nil mask, an empty bounds, and its advance.

func (*Face) GlyphMaskIndexAt added in v0.21.0

func (fc *Face) GlyphMaskIndexAt(gid GlyphIndex, x float64, y int) (bounds image.Rectangle, mask *image.Alpha, advance float64, ok bool)

GlyphMaskIndexAt is Face.GlyphMaskIndex with a FRACTIONAL pen position: the glyph is rasterised with its origin at the nearest of SubpixelPhases horizontal positions in the pixel, so a caller that keeps its pen in a unit finer than the pixel (the exact advances Face.AdvanceIndexUnits times Face.Scale) lays a line out as a browser does, instead of rounding every advance to a whole pixel. Combined with Font.NewFaceAt the outlines are drawn at the exact size as well.

x is the pen origin on the baseline in pixels (fractional), y the baseline row. bounds is the destination rectangle of mask, mask a coverage mask, advance the glyph's own horizontal advance in pixels, UNROUNDED. ok is false when gid is out of range or its outline is corrupt. A valid-but-empty glyph (a space) returns ok true with a nil mask and its advance. Masks are cached per glyph and phase and must not be modified.

func (*Face) GlyphOutline added in v0.6.0

func (fc *Face) GlyphOutline(gid GlyphIndex) (segs []Segment, ok bool)

GlyphOutline returns glyph gid's outline as path segments in font design units, in the font's native Y-up orientation with the pen origin at (0, 0).

TrueType off-curve points are emitted as SegQuadTo control points, with the implied on-curve midpoint synthesised between two consecutive off-curve points. CFF/CFF2 outlines are stored by this package pre-flattened to polylines, so they yield SegLineTo segments only.

ok is false when gid is out of range or its outline is corrupt; a valid but empty glyph (for example a space) returns nil, true.

func (*Face) GlyphOutlineCost added in v0.25.0

func (fc *Face) GlyphOutlineCost(gid GlyphIndex) (segs []Segment, cost int, err error)

GlyphOutlineCost is Face.GlyphOutline together with the Face.GlyphCost of the glyph, from the one interpretation: a caller that bounds a font while it draws it does not outline twice. On error segs is nil and cost is 0.

func (*Face) GlyphSVGPath added in v0.6.0

func (fc *Face) GlyphSVGPath(gid GlyphIndex) (d string, ok bool)

GlyphSVGPath returns glyph gid's outline as an SVG path "d" string at the face's pixel size, in SVG's Y-down coordinate space with the pen origin at (0, 0) — so the baseline is y = 0 and ascenders have negative y. Callers place the glyph by wrapping the path in a translate transform.

ok is false when gid is out of range or its outline is corrupt; a valid but empty glyph returns "", true.

func (*Face) GlyphSVGPathCost added in v0.25.0

func (fc *Face) GlyphSVGPathCost(gid GlyphIndex) (d string, cost int, err error)

GlyphSVGPathCost is Face.GlyphSVGPath together with the Face.GlyphCost of the glyph, from the one interpretation. On error d is "" and cost is 0.

func (*Face) ItalicCorrection added in v0.4.0

func (fc *Face) ItalicCorrection(gid GlyphIndex) int

ItalicCorrection returns glyph gid's math italic correction in pixels, or 0 when the glyph has none (or the font carries no MATH table). It is the space to insert after a slanted glyph before a following upright one, and the horizontal offset for a subscript that follows a superscript.

func (*Face) ItalicCorrectionUnits added in v0.19.0

func (fc *Face) ItalicCorrectionUnits(gid GlyphIndex) float64

ItalicCorrectionUnits is ItalicCorrection without the rounding.

The spec adds this value to a glyph's advance in one case — "when a run of slanted characters is followed by a straight character (such as an operator or a delimiter), the italics correction of the last glyph is added to its advance width" — and uses halves of it to place limits above and below. A quantity that is halved cannot be delivered pre-rounded: on STIXTwoMath at 10pt, 840 of the font's 882 non-zero corrections do not survive the round trip.

func (*Face) Kern added in v0.2.0

func (fc *Face) Kern(prev, r rune) int

Kern returns the horizontal kerning adjustment between the consecutive runes prev and r, in whole pixels at the face's size. GPOS pair positioning is preferred; the legacy kern table is used as a fallback. It is zero when either rune is unmapped or the font carries no kerning for the pair.

The result is rounded to a whole pixel. A text layer that sets type at (or near) the font's own em — where one pixel spans a large design quantum and a single-pixel kern would quantise away most of the sub-pixel pair adjustment — should measure with KernUnits (or KernIndexUnits) instead, which return the unrounded font-unit value, exactly as AdvanceIndexUnits complements AdvanceIndex.

Example

ExampleFace_Kern shows kerning-aware measurement: MeasureKerned folds in the pair adjustment that plain Measure does not.

package main

import (
	"fmt"
	"os"

	"github.com/go-opentype/opentype"
)

// loadTestFont reads the CFF/OpenType font bundled under testdata for the
// examples below (Adobe Source Serif 4, SIL Open Font License; see
// testdata/OFL.txt).
func loadTestFont() *opentype.Font {
	b, err := os.ReadFile("testdata/SourceSerif4-Regular.otf")
	if err != nil {
		panic(err)
	}
	f, err := opentype.Parse(b)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	f := loadTestFont()
	face := f.NewFace(16)

	fmt.Println("Kern('A','V') =", face.Kern('A', 'V'))
	fmt.Println("Measure(\"AV\") =", face.Measure("AV"))
	fmt.Println("MeasureKerned(\"AV\") =", face.MeasureKerned("AV"))
}
Output:
Kern('A','V') = -2
Measure("AV") = 22
MeasureKerned("AV") = 20

func (*Face) KernIndexUnits added in v0.11.0

func (fc *Face) KernIndexUnits(left, right GlyphIndex) float64

KernIndexUnits returns the horizontal kerning adjustment between the consecutive glyphs left and right in font units (unrounded) — the value Kern scales and rounds to pixels. GPOS pair positioning is preferred; the legacy kern table is the fallback. It is the by-glyph-index, font-unit counterpart of Kern, the exact primitive a shaper or a text engine wants: kerning applies between shaped glyphs (which may be ligatures), and a caller typesetting at the design em keeps the sub-pixel adjustment that Kern's whole-pixel rounding would discard. A caller multiplies the result by Face.Scale to obtain pixels (mirroring AdvanceIndexUnits). The adjustment is zero when the font carries no kerning for the pair. ⛔⛔ AND IT IS NOT AUTHORITATIVE FOR EVERY FONT. "The adjustment is zero when the font carries no kerning for the pair" is true only of fonts whose kerning is in pair-adjustment lookups. A font that kerns through GPOS type 7 or 8 also gets a zero here, and the two are indistinguishable. Ask KerningIsContextual once per face: when it is true, this answer is a floor and the shaping path is the one with the sequence a contextual rule needs.

func (*Face) KernUnits added in v0.11.0

func (fc *Face) KernUnits(prev, r rune) float64

KernUnits returns the horizontal kerning adjustment between the consecutive runes prev and r in font units (unrounded) — the rune-keyed, font-unit counterpart of Kern. Each rune maps through the cmap; the result is zero when either rune is unmapped or the font carries no kerning for the pair. A caller multiplies by Face.Scale to obtain pixels; see KernIndexUnits for the by-glyph-index form a shaper drives on an already-substituted run.

func (*Face) KerningIsContextual added in v0.22.0

func (fc *Face) KerningIsContextual() bool

KerningIsContextual reports whether a pair query — Kern, KernUnits, KernIndexUnits, MeasureKerned — can speak for this font's kerning at all.

It is false for the ordinary case: the font's `kern` feature is pair adjustment, and the pair APIs answer it exactly. It is true when any kern lookup is a contextual one (GPOS type 7 or 8), which a pair query cannot evaluate because such a rule is matched against the glyphs AROUND a position. Those pairs then come back 0 from the pair APIs and are adjusted by ShapePositioned / ShapePositionedUnits, so the two disagree about the same font.

A text engine that steers by kerning should ask this once per face and either drive the shaping path or record that its figures are a floor. Returning 0 and saying nothing is how go-tex/engine#716's 1.12pt per "AV" stayed invisible to every number that measurement steers by.

func (*Face) MathConstant added in v0.4.0

func (fc *Face) MathConstant(which MathConstant) int

MathConstant returns the MathConstants value which, pixel-scaled at the face's size — except the three percentage constants, which are pure ratios and returned verbatim. It returns 0 when the font has no MATH constants or which is out of range.

func (*Face) MathConstantUnits added in v0.19.0

func (fc *Face) MathConstantUnits(which MathConstant) float64

MathConstantUnits is MathConstant without the rounding: the value in pixels at the face's size, as a fraction. The three percentage constants are pure ratios and come back verbatim, as they do from MathConstant.

AxisHeight is the one to reach for first and the one that shows why this exists: on STIXTwoMath at 10pt it is 2.58, and MathConstant answers 3.

func (*Face) MathKern added in v0.4.0

func (fc *Face) MathKern(gid GlyphIndex, corner MathKernCorner, correctionHeight int) int

MathKern returns the math cut-in kern (in pixels) for glyph gid at the given corner and correction height, the height (in pixels above the baseline) at which the adjacent script attaches. It returns 0 when the glyph has no kern for that corner or the font carries no MATH table.

func (*Face) MathKernUnits added in v0.19.0

func (fc *Face) MathKernUnits(gid GlyphIndex, corner MathKernCorner, correctionHeight float64) float64

MathKernUnits is MathKern with neither rounding: correctionHeight arrives in pixels as a fraction and the kern comes back the same way.

⛔ MathKern quantises TWICE — it rounds the caller's height back into design units and then rounds the kern — so a caller holding a fractional attachment height has to throw it away before asking, and gets a whole pixel back. The cut-in kern exists to tuck a script into the slope of a glyph, which is a sub-point adjustment or nothing at all.

func (*Face) MathVariants added in v0.4.0

func (fc *Face) MathVariants(gid GlyphIndex, vertical bool) ([]MathVariant, *MathAssembly)

MathVariants returns the size variants and the stretchy-glyph assembly for glyph gid along the requested axis (vertical when vertical is true, otherwise horizontal), with every measurement pixel-scaled at the face's size. Variants are ordered smallest-first as stored in the font; the assembly is nil when the glyph has no assembly recipe. Both results are nil when the glyph has no construction on that axis (or the font carries no MATH table). A math layout engine picks the first variant whose advance meets the target size, or builds the assembly when even the largest variant is too small.

func (*Face) MathVariantsUnits added in v0.26.0

func (fc *Face) MathVariantsUnits(gid GlyphIndex, vertical bool) ([]MathVariantUnits, *MathAssemblyUnits)

MathVariantsUnits is MathVariants without the rounding. The OpenType MATH table stores every one of these measurements in design units (MathGlyphVariantRecord advanceMeasurement, GlyphPart startConnectorLength / endConnectorLength / fullAdvance, MathGlyphConstruction italicsCorrection, MathVariants minConnectorOverlap) and prescribes no rounding; a layout that picks the first variant reaching a target, or sums an assembly's parts, compares and accumulates these quantities, and rounding each to a whole pixel first moves the choice and the total by up to half a pixel per term.

func (*Face) Measure

func (fc *Face) Measure(s string) int

⛔ Measure sums ROUNDED advances, so its error compounds with the length of s rather than staying under half a pixel: it is the sum of each rune's Advance, not the rounded sum of the exact advances. For a measurement a layout decision depends on, accumulate AdvanceUnits and round once at the end.

Measure returns the total advance width of s in pixels (the sum of each rune's Advance).

func (*Face) MeasureKerned added in v0.2.0

func (fc *Face) MeasureKerned(s string) int

MeasureKerned returns the total advance width of s in pixels like Measure, but additionally applies the font's kerning between each pair of consecutive runes. For a font with no kerning it equals Measure.

func (*Face) Metrics

func (fc *Face) Metrics() Metrics

Metrics returns the face's vertical metrics in pixels. When a variation is set and the font carries an MVAR table, the global metric deltas for the ascender ("hasc"), descender ("hdsc") and line gap ("hlgp") are folded in.

func (*Face) Scale added in v0.3.1

func (fc *Face) Scale() float64

Scale returns the face's font-unit-to-pixel scale factor (the render size in pixels divided by the font's unitsPerEm). A shaper multiplies a font-unit advance or offset by it to obtain whole pixels at the face's size.

func (*Face) SetHinting added in v0.2.0

func (fc *Face) SetHinting(on bool)

SetHinting enables or disables the TrueType instruction interpreter. When enabled, a glyf glyph that carries instructions is grid-fitted at the face's pixel size before rasterising; glyphs without instructions, composite glyphs and CFF fonts are unaffected. Hinting is off by default (the default output is unhinted anti-aliased coverage). The glyph cache is invalidated.

func (*Face) SetStemDarkening added in v0.3.7

func (fc *Face) SetStemDarkening(on bool)

SetStemDarkening enables or disables stem darkening (weight compensation) for CFF/CFF2 glyphs. When both hinting and darkening are on, every grid-fitted stem is embiggened by a small ppem-dependent amount (strongest at small sizes, fading to none at larger sizes) so stems keep enough contrast on the anti-aliased rasteriser at small text sizes, as FreeType's CFF engine does by default. It has no effect while hinting is off or on glyf (TrueType) outlines. Darkening is off by default, so the default hinted output is byte-identical to the undarkened result. The glyph cache is invalidated.

func (*Face) SetVariation added in v0.2.0

func (fc *Face) SetVariation(coords map[string]float64)

SetVariation instances the font at the user-space axis coordinates coords (keyed by axis tag, e.g. {"wght": 700}); axes absent from coords take their default. Subsequent GlyphMask calls reflect the instanced outlines, for both glyf (via gvar) and CFF2 (via its blend/vsindex operators) variable fonts. Pass nil to return to the default master. A non-variable font (or a CFF1 font, which has no variation) is unaffected. The glyph cache is invalidated so the change takes effect at once.

func (*Face) Shape added in v0.2.0

func (fc *Face) Shape(text string, features ...string) []GlyphIndex

Shape maps text to its glyph run and applies the GSUB lookups activated by the given feature tags (for example "liga" for standard ligatures, "smcp" for small caps). Each rune maps through the font's cmap; an unmapped rune becomes glyph 0 (.notdef). With no GSUB table, no features, or features that match no lookups, the run is the plain cmap mapping.

Example

ExampleFace_Shape runs the font's own GSUB/GPOS tables through Shape and ShapePositioned to turn a rune run into glyph indices and pen-relative positions, without any external shaping engine.

package main

import (
	"fmt"
	"os"

	"github.com/go-opentype/opentype"
)

// loadTestFont reads the CFF/OpenType font bundled under testdata for the
// examples below (Adobe Source Serif 4, SIL Open Font License; see
// testdata/OFL.txt).
func loadTestFont() *opentype.Font {
	b, err := os.ReadFile("testdata/SourceSerif4-Regular.otf")
	if err != nil {
		panic(err)
	}
	f, err := opentype.Parse(b)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	f := loadTestFont()
	face := f.NewFace(16)

	glyphs := face.Shape("Hi")
	fmt.Println("glyphs =", glyphs)

	for _, g := range face.ShapePositioned("Hi") {
		fmt.Printf("glyph=%d dx=%d dy=%d adv=%d\n", g.Glyph, g.XOffset, g.YOffset, g.XAdvance)
	}
}
Output:
glyphs = [9 36]
glyph=9 dx=0 dy=0 adv=13
glyph=36 dx=0 dy=0 adv=5

func (*Face) ShapeAlternate added in v0.27.0

func (fc *Face) ShapeAlternate(text string, alt int, features ...string) []GlyphIndex

ShapeAlternate is Shape with the alternate of an alternate-substitution (GSUB type 3) lookup chosen by the caller: alt is a 0-based index, and an index past the end of a glyph's set takes its last alternate. Shape is ShapeAlternate with alt 0.

It exists for the "ssty" (math script-style alternates) feature. The OpenType registered-features chapter (features_pt, 'ssty') recommends a type 3 lookup whose first alternate serves script level 1 and whose second serves level 2, "or single substitution" when no second level exists, so a typesetter asks ShapeAlternate(s, 0, "ssty") for a first-order script and ShapeAlternate(s, 1, "ssty") for a second-order one. A type 1 lookup is unaffected by alt, and an index past a glyph's set takes its last alternate.

func (*Face) ShapePositioned added in v0.3.0

func (fc *Face) ShapePositioned(text string, features ...string) []PositionedGlyph

ShapePositioned maps text to a fully positioned glyph run: each rune maps through the cmap (an unmapped rune becomes glyph 0), the requested GSUB features are applied (ligatures, contextual substitution, ...), then GPOS positions the resulting glyphs — pair kerning, single/cursive adjustment and mark attachment (types 4/5/6 pull diacritics onto their base). The positioning features are the caller's features plus the always-on kern/mark/mkmk set.

The result has one PositionedGlyph per output glyph, with placement and advance in whole pixels at the face's size. A font lacking GSUB or GPOS simply skips that stage; with neither the run is the plain cmap mapping at its unadjusted advances. ⛔ IT ROUNDS EACH GLYPH'S PLACEMENT AND ADVANCE, and for a run that is the worst place to do it: the error does not stay under half a pixel, it accumulates along the line. A typesetter wants ShapePositionedUnits.

func (*Face) ShapePositionedUnits added in v0.20.0

func (fc *Face) ShapePositionedUnits(text string, features ...string) []PositionedGlyphUnits

ShapePositionedUnits is ShapePositioned with no rounding: the run a caller gets when it intends to place glyphs at a fraction of a pixel.

⛔⛔ WHY THIS DECIDES WHETHER SHAPING CAN BE SHARED AT ALL. The whole point of ShapePositioned is that a text engine should not hand-roll cmap + ligatures + kerning + mark attachment for itself. But its result was integral, and a consumer that sets type at 10pt — where one pixel is one point — cannot accept half a point of error per glyph. So the engine that most needed this call measured its own advances instead (AdvanceIndexUnits × Scale, exact) and got NO ligatures and NO mark attachment as the price of keeping its metrics: the correct, shared path was lossier than the hand-rolled one it replaced.

The computation was always exact — advances and GPOS adjustments are carried in font units right up to the last three lines — so this adds no arithmetic. It stops throwing the precision away at the door, and ShapePositioned is now this function rounded, which is the only way the two cannot drift apart.

func (*Face) Size added in v0.17.1

func (fc *Face) Size() float64

Size returns the face's em size in pixels, as it was asked for — fractional when the face was built with Font.NewFaceAt. Face.Scale is this divided by the font's unitsPerEm.

func (*Face) TopAccentAttachment added in v0.4.0

func (fc *Face) TopAccentAttachment(gid GlyphIndex) (int, bool)

TopAccentAttachment returns the x position (in pixels from the glyph origin) at which a top accent should be centred over glyph gid. ok is false when the glyph has no entry, in which case a layout engine centres on the glyph's advance instead.

func (*Face) TopAccentAttachmentUnits added in v0.19.0

func (fc *Face) TopAccentAttachmentUnits(gid GlyphIndex) (float64, bool)

TopAccentAttachmentUnits is TopAccentAttachment without the rounding: an accent is CENTRED on this x, so half of any error in it is visible as the accent sitting off-centre over its base.

func (*Face) VerticalAdvance added in v0.3.0

func (fc *Face) VerticalAdvance(r rune) int

VerticalAdvance returns the vertical advance (advance height) of r in pixels, or 0 if the rune is not mapped by the font's cmap. When the font has no vmtx table the advance is one em, scaled to the face's size.

This is the top-to-bottom analogue of Advance. Choosing the upright vertical glyph form for r (the 'vert'/'vrt2' features) is a separate shaping step done through GSUB; VerticalAdvance measures whichever glyph the cmap maps.

func (*Face) VerticalAdvanceIndex added in v0.5.0

func (fc *Face) VerticalAdvanceIndex(gid GlyphIndex) int

VerticalAdvanceIndex returns the vertical advance (advance height) of glyph gid in whole pixels at the face's size, honouring the face's current variation (the VVAR delta is folded in). When the font has no vmtx table the advance is one em. It is the by-glyph-index counterpart of Face.VerticalAdvance.

func (*Face) VerticalMetrics added in v0.3.0

func (fc *Face) VerticalMetrics() (ascent, descent, lineGap int)

VerticalMetrics returns the face's vertical-layout line metrics in pixels: the vhea vertTypoAscender, vertTypoDescender and vertTypoLineGap scaled to the face's size. All three are zero when the font has no vhea table.

func (*Face) VerticalOrigin added in v0.3.0

func (fc *Face) VerticalOrigin(r rune) (int, bool)

VerticalOrigin returns the y coordinate of r's vertical origin in pixels and whether the font supplies one (a VORG table). The origin locates the glyph relative to the pen when advancing top-to-bottom; ok is false when r is unmapped or the font has no VORG table.

type FeatureApp added in v0.3.1

type FeatureApp struct {
	Tag       string
	Positions []bool
}

FeatureApp requests one GSUB feature applied over a subset of a glyph run. Tag is the 4-byte feature tag (for example "init" or "liga"). Positions selects, by run index, the glyphs the feature's lookups may start at: a lookup is attempted at glyph i only when Positions[i] is true. A nil Positions applies the feature over the whole run (identical to Apply); a non-nil Positions restricts it, with indices at or past its end treated as false.

Masking is intended for the length-preserving single substitutions OpenType files the Arabic positional-form features (isol/init/medi/fina) as, so the mask indices stay aligned to the run as it is rewritten.

type Font

type Font struct {
	// contains filtered or unexported fields
}

Font is a parsed TrueType/OpenType font. It is immutable after Parse and safe for concurrent use by multiple goroutines. Build a Face from it with NewFace to obtain sized metrics and rasterised glyphs.

func Parse

func Parse(b []byte) (*Font, error)

Parse decodes a TrueType/OpenType font from b and returns a Font. The byte slice is retained (not copied) and must not be mutated by the caller.

It fails on a corrupt or unsupported container: a bad sfnt magic, truncated data, or a missing required table — which does not include the character map: see Font.HasCharacterMap. All three outline flavours are supported: TrueType ('glyf'/'loca'), CFF/OpenType (a "OTTO" sfnt, or any sfnt carrying a 'CFF ' table, decoded via cff.go) and variable CFF2 (a sfnt carrying a 'CFF2' table, decoded via cff2.go).

Example

ExampleParse parses a font blob and reports its glyph count.

package main

import (
	"fmt"
	"os"

	"github.com/go-opentype/opentype"
)

// loadTestFont reads the CFF/OpenType font bundled under testdata for the
// examples below (Adobe Source Serif 4, SIL Open Font License; see
// testdata/OFL.txt).
func loadTestFont() *opentype.Font {
	b, err := os.ReadFile("testdata/SourceSerif4-Regular.otf")
	if err != nil {
		panic(err)
	}
	f, err := opentype.Parse(b)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	f := loadTestFont()
	fmt.Println(f.NumGlyphs())
}
Output:
1464

func ParseCFF added in v0.8.0

func ParseCFF(b []byte) (*Font, error)

ParseCFF decodes a bare CFF font program — a Compact Font Format font that is not wrapped in an sfnt container, which is how a PDF carries one as a FontFile3 of subtype Type1C. Such a program has no head, no hmtx and no character map: the size of its units comes from its font matrix, its advances from the charstrings themselves, and the way from a name or a byte to a glyph from its own charset and encoding. Font.HasCharacterMap is false for the result, and Font.GlyphIndexByName and Font.GlyphIndexByCode are how it is addressed.

The byte slice is retained, not copied, and must not be mutated afterwards.

func ParseType1 added in v0.9.0

func ParseType1(b []byte) (*Font, error)

ParseType1 decodes a PostScript Type 1 font program — what a PDF carries as a FontFile, and what a .pfb or .pfa file holds. Such a program addresses its glyphs by name and carries an encoding of its own, so the result answers Font.GlyphIndexByName and Font.GlyphIndexByCode and reports no character map.

The bytes are not retained: a Type 1 program is decrypted on the way in, so what is kept is the plaintext.

func (*Font) Ascent added in v0.5.0

func (f *Font) Ascent() int

Ascent returns the typographic ascender in font units (hhea.ascender): the height above the baseline. It is the same value Face.Metrics scales to pixels.

func (*Font) Axes added in v0.2.0

func (f *Font) Axes() []Axis

Axes returns the font's variation axes, or nil for a non-variable font.

func (*Font) CapHeight added in v0.5.0

func (f *Font) CapHeight() int

CapHeight returns the cap height in font units (OS/2.sCapHeight). It is zero when the font has no OS/2 table or an OS/2 version below 2, which do not carry it; a PDF consumer that needs a non-zero value substitutes the ascender.

func (*Font) CharacterMap added in v0.12.0

func (f *Font) CharacterMap(i int) (platform, encoding, format uint16, ok bool)

CharacterMap reports which platform and encoding the i'th subtable was written for, and which format it is written in. ok is false when i is not the index of a subtable.

The pairs worth recognising are (3,1) and (3,10), Microsoft Unicode, and platform 0, Unicode; (3,0), Microsoft Symbol, whose codes are the font's own and conventionally live at 0xF000 + code; and (1,0), Macintosh Roman.

func (*Font) Descent added in v0.5.0

func (f *Font) Descent() int

Descent returns the typographic descender in font units (hhea.descender). It is conventionally negative (below the baseline), as stored in hhea.

func (*Font) Flags added in v0.5.0

func (f *Font) Flags() int

Flags returns the PDF FontDescriptor /Flags value for the font: a bit set combining FixedPitch, Serif, Symbolic-or-Nonsymbolic and Italic, derived from the post, OS/2 and head tables. A caller embeds it verbatim as /Flags. Exactly one of the Symbolic and Nonsymbolic bits is always set.

func (*Font) FontBBox added in v0.5.0

func (f *Font) FontBBox() (xMin, yMin, xMax, yMax int)

FontBBox returns the font bounding box in font units (head.xMin/yMin/xMax/yMax): the union of every glyph's bounds. A PDF FontDescriptor's /FontBBox is this box scaled to glyph space.

func (*Font) GPOS added in v0.3.1

func (f *Font) GPOS() *GPOS

GPOS returns the font's parsed GPOS table, or nil when the font carries no GPOS table (in which case no positioning is available).

func (*Font) GSUB added in v0.3.1

func (f *Font) GSUB() *GSUB

GSUB returns the font's parsed GSUB table, or nil when the font carries no GSUB table (in which case no substitution is available).

func (*Font) GlyphAdvance added in v0.3.1

func (f *Font) GlyphAdvance(g GlyphIndex) int

GlyphAdvance returns the horizontal advance of glyph g in font units, or 0 when g is out of range. A shaper multiplies it by Face.Scale to obtain pixels, and feeds the per-glyph advances to [GPOS.Position] so mark attachment can pull a diacritic back onto its base.

func (*Font) GlyphIndex

func (f *Font) GlyphIndex(r rune) (GlyphIndex, bool)

GlyphIndex maps a rune to its glyph index via the selected cmap subtable. ok is false when the rune has no glyph in that subtable, and for a font that carries no character map at all — one addressed by glyph number, which Font.HasCharacterMap reports.

func (*Font) GlyphIndexByCID added in v0.10.0

func (f *Font) GlyphIndexByCID(cid int) (GlyphIndex, bool)

GlyphIndexByCID maps a character identifier to a glyph, for a CFF font addressed by identifier rather than by name.

A composite font in a PDF names its glyphs by identifier, and how an identifier reaches a glyph depends on which sort of font program carries them. A TrueType-based one says so in a map of its own, and where it says nothing the identifier is the glyph number. A CFF-based one says nothing of the kind: the mapping lives in the font program's own charset, which for such a font lists, for each glyph in order, the identifier it stands for.

Taking the identifier for the glyph number, as a reader must for the other sort, is wrong here by construction, and wrong in the worse of the two ways: when the number lands past the end of the font nothing is drawn, but when it lands inside it — which it usually does — a real glyph is drawn and it is the wrong one. Of the CID-keyed CFF fonts found on pages that came out blank, every one of fifty-five had a charset that was not the identity; of those in the figure corpus, twenty-one of forty-seven.

ok is false for a font that is not addressed by identifier, and for one whose charset does not name that identifier at all.

func (*Font) GlyphIndexByCode added in v0.8.0

func (f *Font) GlyphIndexByCode(code byte) (GlyphIndex, bool)

GlyphIndexByCode maps a byte to a glyph through the font program's own built-in encoding — the Standard Encoding unless the program said otherwise. ok is false for a font that carries no such encoding, which is every TrueType font and every CFF font addressed by character identifier.

func (*Font) GlyphIndexByName added in v0.8.0

func (f *Font) GlyphIndexByName(name string) (GlyphIndex, bool)

GlyphIndexByName maps a glyph name to its index. ok is false when the font names no glyphs or has none of that name.

func (*Font) GlyphIndexInMap added in v0.12.0

func (f *Font) GlyphIndexInMap(i int, code rune) (GlyphIndex, bool)

GlyphIndexInMap maps a code to a glyph through one named subtable rather than through the one the font would choose. ok is false when i is not the index of a subtable, or when that subtable does not map the code (including a mapping to the .notdef glyph).

The code is whatever the subtable is indexed by: a Unicode codepoint for a Unicode subtable, and a raw byte of the font's own encoding for a Microsoft Symbol or Macintosh Roman one.

func (*Font) GlyphIndexVariation added in v0.2.0

func (f *Font) GlyphIndexVariation(r, vs rune) (GlyphIndex, bool)

GlyphIndexVariation resolves a Unicode variation sequence (a base rune followed by a variation selector) to a glyph index, using the font's format-14 cmap subtable.

ok is false when the font has no format-14 subtable, the variation selector is not registered in it, or the sequence is registered as a "default" mapping whose base rune has no glyph in the ordinary cmap.

func (*Font) GlyphName added in v0.8.0

func (f *Font) GlyphName(gid GlyphIndex) (string, bool)

GlyphName is what the font calls a glyph. ok is false for a font that does not name its glyphs — a TrueType font usually does not, and a CFF font addressed by character identifier never does.

func (*Font) HasCharacterMap added in v0.7.0

func (f *Font) HasCharacterMap() bool

HasCharacterMap reports whether the font can say which glyph a rune is. A font subset embedded in a PDF as a CIDFontType2 usually cannot: the document carries that map instead, and the font is addressed by glyph number.

func (*Font) HasMath added in v0.4.0

func (f *Font) HasMath() bool

HasMath reports whether the font carries an OpenType MATH table (the metrics a math-typesetting engine needs). When false, all Face math accessors return their zero result.

func (*Font) HasVerticalMetrics added in v0.3.0

func (f *Font) HasVerticalMetrics() bool

HasVerticalMetrics reports whether the font carries the vertical header and per-glyph vertical advances (vhea and vmtx) required to lay text out top-to-bottom. When it returns false, VerticalAdvance falls back to the em square and VerticalMetrics returns zeroes.

func (*Font) Instance added in v0.5.0

func (f *Font) Instance(coords map[string]float64) (*Font, error)

Instance bakes the font at the user-space axis coordinates coords into a new, static Font: a font with the requested variation permanently applied and no variation axes. Axes absent from coords take their default. It is the parsed counterpart of InstanceBytes.

It returns an error for a non-variable font, a CFF2 (variable CFF) font, or when coords names an axis the font does not have.

func (*Font) InstanceBytes added in v0.5.0

func (f *Font) InstanceBytes(coords map[string]float64) ([]byte, error)

InstanceBytes bakes the font at coords into the bytes of a new static TrueType sfnt (see Instance for the semantics). The returned font carries instanced glyf outlines and advance widths and no variation tables; Instance parses these bytes.

func (*Font) InstancePoints added in v0.2.0

func (f *Font) InstancePoints(gid int, coords map[string]float64) ([]contour, error)

InstancePoints returns glyph gid's outline, as contours in font units, instanced at the user-space axis coordinates coords (keyed by axis tag). Axes absent from coords take their default. For a non-variable font, or a glyph with no variation data, it returns the default outline. Both simple and composite glyphs are varied: a composite's component offsets get their deltas and each component is instanced recursively at the same coordinate.

func (*Font) IsCIDKeyed added in v0.10.0

func (f *Font) IsCIDKeyed() bool

IsCIDKeyed says whether the font program is addressed by identifier rather than by name, which is what decides how a composite font's identifiers reach its glyphs.

func (*Font) IsExtendedShapeGlyph added in v0.4.0

func (f *Font) IsExtendedShapeGlyph(gid GlyphIndex) bool

IsExtendedShapeGlyph reports whether gid is in the MATH table's extended-shape coverage: a tall glyph (such as a large integral) whose superscript is positioned as if the glyph were a stretched, rather than a fixed-size, shape.

func (*Font) IsFixedPitch added in v0.5.0

func (f *Font) IsFixedPitch() bool

IsFixedPitch reports whether the font is monospaced (post.isFixedPitch).

func (*Font) IsItalic added in v0.5.0

func (f *Font) IsItalic() bool

IsItalic reports whether the font is italic or oblique, from any of the three places a font may record it: a non-zero post italic angle, the head macStyle italic bit, or the OS/2 fsSelection italic bit.

func (*Font) IsSerif added in v0.5.0

func (f *Font) IsSerif() bool

IsSerif reports whether the font is a serif design, read from the high byte of OS/2.sFamilyClass (the IBM font-class id): classes 1-7 are serif families, class 8 is sans-serif, and the rest (script, symbolic, ...) are neither. It is false when the font has no OS/2 table.

func (*Font) ItalicAngle added in v0.5.0

func (f *Font) ItalicAngle() float64

ItalicAngle returns the italic (slant) angle in counter-clockwise degrees from vertical (post.italicAngle): zero for an upright font, negative for the usual forward slant. It is zero when the font has no post table.

func (*Font) LineGap added in v0.5.0

func (f *Font) LineGap() int

LineGap returns the typographic line gap in font units (hhea.lineGap): the recommended extra spacing between lines beyond ascent minus descent.

func (*Font) NamedInstances added in v0.2.0

func (f *Font) NamedInstances() []NamedInstance

NamedInstances returns the font's named instances, or nil if the font is not variable or declares none.

func (*Font) NewFace

func (f *Font) NewFace(sizePx int) *Face

NewFace returns a Face that renders f at sizePx pixels per em. The scale factor is sizePx / unitsPerEm; sizePx should be positive.

For a size that is not a whole number of pixels, use Font.NewFaceAt.

Example

ExampleFont_NewFace builds a sized Face and measures a string, mirroring the narrow slice of golang.org/x/image/font/opentype this package replaces.

package main

import (
	"fmt"
	"os"

	"github.com/go-opentype/opentype"
)

// loadTestFont reads the CFF/OpenType font bundled under testdata for the
// examples below (Adobe Source Serif 4, SIL Open Font License; see
// testdata/OFL.txt).
func loadTestFont() *opentype.Font {
	b, err := os.ReadFile("testdata/SourceSerif4-Regular.otf")
	if err != nil {
		panic(err)
	}
	f, err := opentype.Parse(b)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	f := loadTestFont()
	face := f.NewFace(16) // 16px per em

	m := face.Metrics()
	fmt.Println("ascent", m.Ascent, "descent", m.Descent, "height", m.Height)
	fmt.Println("Measure(Hello) =", face.Measure("Hello"))
	fmt.Println("Advance('H') =", face.Advance('H'))
}
Output:
ascent 17 descent 5 height 22
Measure(Hello) = 40
Advance('H') = 13

func (*Font) NewFaceAt added in v0.17.1

func (f *Font) NewFaceAt(size float64) *Face

NewFaceAt returns a Face that renders f at size pixels per em, where size may be FRACTIONAL. The metric scale is size / unitsPerEm exactly.

The OpenType specification allows this. head.flags bit 3 reads "Force ppem to integer values for all internal scaler math; may use fractional ppem sizes if this bit is clear. It is strongly recommended that this be set in hinted fonts." — so the integer constraint belongs to the SCALER, not to the metrics, and this Face keeps the two apart: fc.scale is exact, while the whole-pixel ppem the TrueType interpreter and CFF stem darkening need is the rounded value.

⛔⛔ WHY THIS EXISTS. A caller that works in a unit finer than the pixel cannot express its sizes through an int. LaTeX's size ladder is a table of fractional points — \Large is 14.4pt, \LARGE 17.28, \huge 20.74 — and go-tex, which measures in scaled points (1/65536 pt), was obliged to round every step to a whole pixel before asking for a face: \Large came out at 14, 2.8% narrow, on every section heading of every document (go-opentype/opentype#61).

Such a caller already reads metrics in FONT UNITS and scales them itself — AdvanceIndexUnits, KernUnits — precisely to avoid this library's own rounding. That arithmetic was exact in every term but one: Scale() itself was anchored on an integer. This is the term.

func (*Font) NormalizeCoords added in v0.2.0

func (f *Font) NormalizeCoords(user map[string]float64) []int16

NormalizeCoords converts a set of user-space axis coordinates (keyed by axis tag) into per-axis normalized F2Dot14 values in the range [-1, 1], the form gvar and avar operate in. Axes not present in user take their default (which normalizes to 0). Values outside an axis's [min, max] are clamped. If the font declares an 'avar' table its segment maps are applied. The result has one entry per fvar axis, in axis order; it is nil for a non-variable font.

func (*Font) NumCharacterMaps added in v0.12.0

func (f *Font) NumCharacterMaps() int

NumCharacterMaps returns how many cmap subtables the font carries in a form this package decodes. It is zero for a font with no character map at all.

Format 14 (Unicode Variation Sequences) is not one of them: it maps a pair rather than a code, and is reached through Font.GlyphIndexVariation.

func (*Font) NumGlyphs

func (f *Font) NumGlyphs() int

NumGlyphs returns the number of glyphs in the font (from the maxp table).

func (*Font) RuneOfGlyphInMap added in v0.12.0

func (f *Font) RuneOfGlyphInMap(i int, gid GlyphIndex) (rune, bool)

RuneOfGlyphInMap inverts one subtable: which code reaches this glyph. ok is false when i is not the index of a subtable, or when no code in it reaches that glyph.

A subtable maps many codes onto one glyph — a space and a no-break space commonly share one — and the lowest of them is the one reported. Inverting a Unicode subtable is how the character a glyph stands for is recovered when the document says nothing about it and the program names nothing: the font itself said which codepoint that glyph is for.

The inverse is built once per subtable, on the first call, and kept.

func (*Font) StemV added in v0.5.0

func (f *Font) StemV() int

StemV returns an estimate, in font units, of the dominant vertical stem width a PDF FontDescriptor requires as /StemV. OpenType fonts do not store StemV, so it is approximated from the OS/2 weight class with the linear relation 50 + (weightClass-100)*11/100 (about 83 at the normal weight 400, ~116 at bold 700), clamped to a floor of 50. A font without an OS/2 table is treated as the normal weight. Callers that can do better should read WeightClass directly.

func (*Font) SubsetCFF added in v0.5.0

func (f *Font) SubsetCFF(gids []GlyphIndex) ([]byte, error)

SubsetCFF builds a subset 'CFF ' table (the raw font program, as a PDF /FontFile3 CIDFontType0C stream embeds it) that keeps the charstrings of the glyphs in gids plus glyph 0, replacing every other glyph's charstring with an empty one. Glyph numbering is preserved, so the font's charset, encoding, Private DICT and subroutines remain valid and a PDF embeds the result with an Identity CIDToGIDMap (no glyph-id remap is needed, unlike SubsetTrueType).

It returns an error for a font with no CFF table (a TrueType font — use SubsetTrueType), for a CFF2 (variable) font, for a CID-keyed CFF (one with a ROS, FDArray or FDSelect operator), or when a requested glyph id is out of range. See the file-level comment for the retained-subroutine and endchar-seac scope notes.

func (*Font) SubsetTrueType added in v0.5.0

func (f *Font) SubsetTrueType(gids []GlyphIndex) (data []byte, oldToNew map[GlyphIndex]GlyphIndex, err error)

SubsetTrueType builds a minimal, valid TrueType sfnt carrying only the glyphs in gids plus glyph 0 and every component a composite among them references. The kept glyphs are renumbered compactly (glyph 0 stays 0); the returned oldToNew map gives each retained original glyph id its id in the subset, which a PDF CIDFontType2 embedder turns into a /CIDToGIDMap (CID = original id -> subset id) and a content-stream writer uses to re-address glyphs.

The rebuilt font contains glyf, loca (long form), head, hhea, maxp, hmtx and a minimal cmap (enough to re-parse; a PDF addresses the subset by glyph id, not through the cmap), plus the TrueType instruction tables (cvt/fpgm/prep) when the original font carried them so hinted glyphs still render as designed. Composite component references are rewritten to the new glyph numbering.

It returns an error for a font with no glyf table (a CFF/OpenType font — use SubsetCFF) or when a requested glyph id is out of range.

func (*Font) Table added in v0.5.0

func (f *Font) Table(tag string) (data []byte, ok bool)

Table returns a copy of the raw bytes of the table named by its four-byte tag, and ok reporting whether the font carries that table. The tag must be the exact sfnt spelling including any trailing space (for example "cvt " or "OS/2"). The returned slice is a fresh copy the caller may retain or mutate; it never aliases the font's backing data.

func (*Font) TableTags added in v0.5.0

func (f *Font) TableTags() []string

TableTags returns the four-byte tags of every table in the font, sorted lexicographically. The returned slice is freshly allocated and owned by the caller. Tags retain their sfnt spelling, including any trailing space (for example "cvt " and "OS/2").

func (*Font) TypoAscent added in v0.17.0

func (f *Font) TypoAscent() int

TypoAscent, TypoDescent and TypoLineGap return OS/2's sTypoAscender, sTypoDescender and sTypoLineGap in font units, and UseTypoMetrics reports the font's own instruction to prefer them.

⭐ THESE, NOT Ascent/Descent/LineGap, ARE WHAT THE SPEC NAMES FOR NEW WORK. OpenType 1.9.1, hhea:

The ascender, descender and linegap values in this table are Apple specific …
The sTypoAscender, sTypoDescender and sTypoLineGap fields in the OS/2 table are
used on the Windows platform, and are recommended for new text-layout
implementations.

and OS/2, sTypoAscender: "This field should be combined with the sTypoDescender and sTypoLineGap values to determine default line spacing … intended to allow applications to lay out documents in a typographically correct and portable fashion."

Ascent, Descent and LineGap keep returning hhea unchanged: they say which table they read, and silently changing what an existing accessor means would reflow every document laid out with this package.

⛔ TypoDescent is NEGATIVE below the baseline. WinDescent is POSITIVE below it — the spec stores it unsigned — so the two cannot be compared or substituted without a sign change.

All five are zero when the font has no OS/2 table, the convention CapHeight already follows. sTypoAscender − sTypoDescender is NOT required to equal UnitsPerEm, and the spec says so explicitly, so a caller must not use that identity as a validity check.

func (*Font) TypoDescent added in v0.17.0

func (f *Font) TypoDescent() int

func (*Font) TypoLineGap added in v0.17.0

func (f *Font) TypoLineGap() int

func (*Font) UnitsPerEm added in v0.5.0

func (f *Font) UnitsPerEm() int

UnitsPerEm returns the font's design units per em (from head), the scale in which every other font-unit metric this package reports is expressed. It is never zero (Parse rejects a font whose head declares zero).

func (*Font) UseTypoMetrics added in v0.17.0

func (f *Font) UseTypoMetrics() bool

UseTypoMetrics reports fsSelection bit 7, USE_TYPO_METRICS: the font's own statement that its sTypo* values, rather than its usWin* values, should decide default line spacing. The bit was defined in OS/2 version 4, so a font with an earlier table always reports false — which is not "prefer usWin*", only "this font does not say".

func (*Font) WeightClass added in v0.5.0

func (f *Font) WeightClass() int

WeightClass returns the OS/2 usWeightClass (100 thin .. 400 normal .. 900 black), or 0 when the font carries no OS/2 table.

func (*Font) WidthClass added in v0.5.0

func (f *Font) WidthClass() int

WidthClass returns the OS/2 usWidthClass (1 ultra-condensed .. 5 normal .. 9 ultra-expanded), or 0 when the font carries no OS/2 table.

func (*Font) WinAscent added in v0.17.0

func (f *Font) WinAscent() int

WinAscent and WinDescent return OS/2's usWinAscent and usWinDescent in font units. WinDescent is POSITIVE below the baseline.

⛔ THESE ARE A CLIPPING EXTENT, NOT LINE SPACING, and the spec is unusually blunt about it: "Some legacy applications use the usWinAscent and usWinDescent values to determine default line spacing. This is strongly discouraged. The sTypo* fields should be used for this purpose." They are the right values for sizing a redraw or selection rectangle, and the wrong ones for leading.

func (*Font) WinDescent added in v0.17.0

func (f *Font) WinDescent() int

func (*Font) XHeight added in v0.5.0

func (f *Font) XHeight() int

XHeight returns the x height in font units (OS/2.sxHeight). It is zero when the font has no OS/2 table or an OS/2 version below 2 (which do not carry it).

type GPOS added in v0.3.1

type GPOS = gpos

GPOS is the exported handle to a font's parsed GPOS (glyph positioning) table, obtained via Font.GPOS. Its [GPOS.Position] method runs positioning lookups (pair kerning, mark attachment, cursive attachment, ...) over a glyph run a caller has already substituted.

type GSUB added in v0.3.1

type GSUB = gsub

GSUB is the exported handle to a font's parsed GSUB (glyph substitution) table, obtained via Font.GSUB. It exposes [GSUB.Apply] (whole-run) and [GSUB.ApplyMasked] (positional) so a shaper outside this package can drive substitution lookups directly.

type GlyphIndex

type GlyphIndex uint16

GlyphIndex is a glyph identifier within a font: an index into the font's glyph store, as produced by the cmap. Zero is the ".notdef" glyph.

type GlyphPosition added in v0.3.0

type GlyphPosition struct {
	XOffset  int
	YOffset  int
	XAdvance int
	YAdvance int
}

GlyphPosition is the positioning adjustment GPOS computes for one glyph in a run: pen placement offsets (XOffset, YOffset) and advance adjustments (XAdvance, YAdvance), all in font units.

type Kerner added in v0.2.0

type Kerner struct {
	// contains filtered or unexported fields
}

Kerner combines GPOS and the legacy kern table: GPOS is preferred and the kern table is a fallback used when GPOS yields no adjustment. Either source may be nil.

func (*Kerner) Kerning added in v0.2.0

func (kn *Kerner) Kerning(left, right GlyphIndex) int

Kerning returns the X-advance adjustment between left and right. GPOS wins wherever it covers the pair, including when it covers it with zero: a pair listed in a pair-adjustment lookup with no adjustment is the font saying "nothing here", which is an answer and not a silence. Only a pair no GPOS lookup mentions falls through to the legacy kern table.

func (*Kerner) KerningIsContextual added in v0.22.0

func (kn *Kerner) KerningIsContextual() bool

KerningIsContextual reports whether this font puts any of its `kern` feature in lookups a pair query cannot evaluate — GPOS types 7 and 8.

When it is true, Kerning and the rune-keyed KernUnits are NOT authoritative for this font: they answer from the pair-adjustment subtables alone and return 0 where a contextual rule would have adjusted. A caller that needs the font's real positioning must drive the shaping path, which has the glyph sequence a contextual rule is evaluated against.

⛔ It is a property of the FONT, not of a pair, and that is the point. The condition cannot be reported per call — kernCovered genuinely does not know whether the contextual lookup it skipped would have matched at some position — so a caller asks once, per face, and decides which path to use. Asked per pair it would have to answer "maybe" every time.

type MathAssembly added in v0.4.0

type MathAssembly struct {
	ItalicsCorrection   int
	MinConnectorOverlap int
	Parts               []MathAssemblyPart
}

MathAssembly is the recipe for building a stretchy glyph out of repeatable parts, with all measurements in pixels at the Face's size. A layout engine stacks the parts (vertically or horizontally), overlapping neighbours by at least MinConnectorOverlap and repeating the Extender parts until the assembly reaches the target size.

type MathAssemblyPart added in v0.4.0

type MathAssemblyPart struct {
	Glyph          GlyphIndex
	StartConnector int
	EndConnector   int
	FullAdvance    int
	Extender       bool
}

MathAssemblyPart is one component of a MathAssembly. StartConnector and EndConnector are the maximum overlap lengths at the part's leading and trailing ends; FullAdvance is the part's full extent along the stretch axis.

type MathAssemblyPartUnits added in v0.26.0

type MathAssemblyPartUnits struct {
	Glyph          GlyphIndex
	StartConnector float64
	EndConnector   float64
	FullAdvance    float64
	Extender       bool
}

MathAssemblyPartUnits is MathAssemblyPart without the rounding.

type MathAssemblyUnits added in v0.26.0

type MathAssemblyUnits struct {
	ItalicsCorrection   float64
	MinConnectorOverlap float64
	Parts               []MathAssemblyPartUnits
}

MathAssemblyUnits is MathAssembly without the rounding.

type MathConstant added in v0.4.0

type MathConstant int

MathConstant identifies one scalar in the MATH table's MathConstants record. The constants are listed in their on-disk order. Face.MathConstant returns each pixel-scaled, except the three percentage constants (ScriptPercentScaleDown, ScriptScriptPercentScaleDown and RadicalDegreeBottomRaisePercent), which are pure ratios and returned verbatim.

const (
	ScriptPercentScaleDown MathConstant = iota
	ScriptScriptPercentScaleDown
	DelimitedSubFormulaMinHeight
	DisplayOperatorMinHeight
	MathLeading
	AxisHeight
	AccentBaseHeight
	FlattenedAccentBaseHeight
	SubscriptShiftDown
	SubscriptTopMax
	SubscriptBaselineDropMin
	SuperscriptShiftUp
	SuperscriptShiftUpCramped
	SuperscriptBottomMin
	SuperscriptBaselineDropMax
	SubSuperscriptGapMin
	SuperscriptBottomMaxWithSubscript
	SpaceAfterScript
	UpperLimitGapMin
	UpperLimitBaselineRiseMin
	LowerLimitGapMin
	LowerLimitBaselineDropMin
	StackTopShiftUp
	StackTopDisplayStyleShiftUp
	StackBottomShiftDown
	StackBottomDisplayStyleShiftDown
	StackGapMin
	StackDisplayStyleGapMin
	StretchStackTopShiftUp
	StretchStackBottomShiftDown
	StretchStackGapAboveMin
	StretchStackGapBelowMin
	FractionNumeratorShiftUp
	FractionNumeratorDisplayStyleShiftUp
	FractionDenominatorShiftDown
	FractionDenominatorDisplayStyleShiftDown
	FractionNumeratorGapMin
	FractionNumDisplayStyleGapMin
	FractionRuleThickness
	FractionDenominatorGapMin
	FractionDenomDisplayStyleGapMin
	SkewedFractionHorizontalGap
	SkewedFractionVerticalGap
	OverbarVerticalGap
	OverbarRuleThickness
	OverbarExtraAscender
	UnderbarVerticalGap
	UnderbarRuleThickness
	UnderbarExtraDescender
	RadicalVerticalGap
	RadicalDisplayStyleVerticalGap
	RadicalRuleThickness
	RadicalExtraAscender
	RadicalKernBeforeDegree
	RadicalKernAfterDegree
	RadicalDegreeBottomRaisePercent
)

The MathConstants record fields, in table order. mathConstCount is the count sentinel (not a real constant).

type MathKernCorner added in v0.4.0

type MathKernCorner int

MathKernCorner selects one of a glyph's four math-kern corners, used for the staircase cut-in between a base glyph and an adjacent script.

const (
	MathKernTopRight MathKernCorner = iota
	MathKernTopLeft
	MathKernBottomRight
	MathKernBottomLeft
)

The four math-kern corners, in the on-disk order of a MathKernInfoRecord.

type MathVariant added in v0.4.0

type MathVariant struct {
	Glyph   GlyphIndex
	Advance int
}

MathVariant is one size variant of a stretchy glyph: the variant's glyph and its advance (height for a vertical variant, width for a horizontal one) in pixels at the Face's size.

type MathVariantUnits added in v0.26.0

type MathVariantUnits struct {
	Glyph   GlyphIndex
	Advance float64
}

MathVariantUnits is MathVariant without the rounding: Advance is the variant's height (vertical) or width (horizontal) in pixels at the Face's size, as a fraction.

type Metrics

type Metrics struct {
	Ascent  int // baseline-to-top distance (a positive height above the baseline)
	Descent int // baseline-to-bottom distance (a positive depth below the baseline)
	Height  int // line height: ascent + descent + line gap
}

Metrics holds a Face's vertical metrics in whole pixels.

type NamedInstance added in v0.2.0

type NamedInstance struct {
	SubfamilyNameID  uint16             // 'name' entry for the instance subfamily
	Flags            uint16             // instance flags (reserved)
	Coordinates      map[string]float64 // axis tag -> user coordinate
	PostScriptNameID uint16             // 'name' entry for the PostScript name, 0 if absent
}

NamedInstance is a named position in the variation space (for example "Bold" or "Condensed"), decoded from the 'fvar' table.

type Point added in v0.6.0

type Point struct{ X, Y float64 }

Point is a 2-D coordinate in a glyph outline.

type PositionedGlyph added in v0.3.0

type PositionedGlyph struct {
	Glyph    GlyphIndex
	XOffset  int
	YOffset  int
	XAdvance int
}

PositionedGlyph is one glyph of a positioned run produced by ShapePositioned: the glyph to draw, the pen-relative placement offsets (XOffset, YOffset) GPOS assigned it (a non-zero YOffset lifts an attached diacritic onto its base), and the advance to move the pen by afterwards, all in whole pixels at the face's size.

type PositionedGlyphUnits added in v0.20.0

type PositionedGlyphUnits struct {
	Glyph    GlyphIndex
	XOffset  float64
	YOffset  float64
	XAdvance float64
}

PositionedGlyphUnits is one glyph of a positioned run produced by ShapePositionedUnits: the same thing PositionedGlyph carries, in pixels at the face's size WITHOUT rounding.

type Segment added in v0.6.0

type Segment struct {
	Op SegmentOp
	P  [2]Point
}

Segment is one command of a glyph outline. SegMoveTo and SegLineTo use P[0]; SegQuadTo uses P[0] as the quadratic control point and P[1] as the on-curve endpoint; SegClose uses neither.

type SegmentOp added in v0.6.0

type SegmentOp uint8

SegmentOp identifies a glyph-outline path command.

const (
	// SegMoveTo starts a new contour at P[0].
	SegMoveTo SegmentOp = iota
	// SegLineTo draws a straight line to P[0].
	SegLineTo
	// SegQuadTo draws a quadratic Bézier with control point P[0] to endpoint P[1].
	SegQuadTo
	// SegClose closes the current contour; it carries no points.
	SegClose
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址