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 ¶
Phase 1 covers TrueType 'glyf' outlines: the sfnt container, the 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. OpenType/CFF ('OTTO') outlines, GPOS/GSUB shaping, kerning and hinting are not implemented; see the README for the full support matrix.
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.
Index ¶
- type Axis
- type Face
- func (fc *Face) Advance(r rune) int
- func (fc *Face) GlyphMask(r rune, x, y int) (bounds image.Rectangle, mask *image.Alpha, maskp image.Point, advance int, ...)
- func (fc *Face) Kern(prev, r rune) int
- func (fc *Face) Measure(s string) int
- func (fc *Face) MeasureKerned(s string) int
- func (fc *Face) Metrics() Metrics
- func (fc *Face) SetHinting(on bool)
- func (fc *Face) SetVariation(coords map[string]float64)
- func (fc *Face) Shape(text string, features ...string) []GlyphIndex
- type Font
- func (f *Font) Axes() []Axis
- func (f *Font) GlyphIndex(r rune) (GlyphIndex, bool)
- func (f *Font) GlyphIndexVariation(r, vs rune) (GlyphIndex, bool)
- func (f *Font) InstancePoints(gid int, coords map[string]float64) ([]contour, error)
- func (f *Font) NamedInstances() []NamedInstance
- func (f *Font) NewFace(sizePx int) *Face
- func (f *Font) NormalizeCoords(user map[string]float64) []int16
- func (f *Font) NumGlyphs() int
- type GlyphIndex
- type Kerner
- type Metrics
- type NamedInstance
Constants ¶
This section is empty.
Variables ¶
This section is empty.
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 ¶
Advance returns the horizontal advance of r in pixels, or 0 if the rune is not mapped by the font's cmap.
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.
func (*Face) Kern ¶ added in v0.2.0
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.
func (*Face) Measure ¶
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
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) SetHinting ¶ added in v0.2.0
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) SetVariation ¶ added in v0.2.0
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 glyf outlines. Pass nil to return to the default master. A non-variable font (or a CFF font) 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.
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 ¶
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. Both outline flavours are supported: TrueType ('glyf'/'loca') and CFF/OpenType (a "OTTO" sfnt, or any sfnt carrying a 'CFF ' table), the latter decoded via cff.go.
func (*Font) Axes ¶ added in v0.2.0
Axes returns the font's variation axes, or nil for a non-variable font.
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.
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) InstancePoints ¶ added in v0.2.0
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. Composite glyphs are returned resolved but with component-offset variation not applied (see the deferred note in this file).
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 ¶
NewFace returns a Face that renders f at sizePx pixels per em. The scale factor is sizePx / unitsPerEm; sizePx should be positive.
func (*Font) NormalizeCoords ¶ added in v0.2.0
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.
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 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, preferring a non-zero GPOS value and otherwise falling back to the legacy kern table.
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.