gofont

package module
v0.0.17-0...-8322323 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2026 License: MIT Imports: 10 Imported by: 0

README

go-font

中文文档

A Go library for parsing, editing, and serializing TrueType (.ttf) and OpenType/CFF (.otf) font files, with support for WOFF, WOFF2, EOT, and TTC formats. It also implements golang.org/x/image/font.Face for rendering text directly onto images.

Installation

go get github.com/venusliang/go-font

Quick Start

package main

import (
    "fmt"
    "os"

    gofont "github.com/venusliang/go-font"
)

func main() {
    // Read a TTF font file
    data, _ := os.ReadFile("myfont.ttf")

    // Parse (also supports .otf files, auto-detected)
    ttf, err := gofont.Parse(data)
    if err != nil {
        panic(err)
    }

    // Inspect font info
    fmt.Printf("Glyph count: %d\n", ttf.NumGlyphs())

    // Serialize back to TTF
    out, _ := ttf.Serialize()
    os.WriteFile("output.ttf", out, 0644)
}

API Overview

Parsing & Serialization
Method Description
Parse(data []byte) (TrueTypeFont, error) Parse TTF/OTF binary data (auto-detects TrueType vs OpenType/CFF)
ParseWOFF(data []byte) (TrueTypeFont, error) Parse WOFF binary data
ParseWOFF2(data []byte) (TrueTypeFont, error) Parse WOFF2 binary data
ParseEOT(data []byte) (TrueTypeFont, error) Parse EOT binary data
ParseTTC(data []byte) ([]TrueTypeFont, error) Parse TTC binary data, returns a list of font objects
ttf.Serialize() ([]byte, error) Serialize to TTF binary data
ttf.SerializeWOFF() ([]byte, error) Serialize to WOFF format
ttf.SerializeWOFF2() ([]byte, error) Serialize to WOFF2 format
ttf.SerializeEOT() ([]byte, error) Serialize to EOT format
SerializeTTC(fonts []TrueTypeFont) ([]byte, error) Serialize multiple fonts into TTC format
Unicode Mapping
Method Description
RuneToGlyphID(r rune) uint16 Map a Unicode code point to a glyph ID; returns 0 if unmapped
GlyphForRune(r rune) *Glyph Get glyph data for a Unicode code point; returns nil if unmapped
SetRuneMapping(r rune, glyphID uint16) error Set a mapping from code point to glyph ID
RemoveRuneMapping(r rune) Remove the mapping for a code point
SetRuneMappings(m map[rune]uint16) error Set multiple mappings at once
RuneMappings() []struct{Rune; GlyphID} Return all mappings, sorted by code point
MappedRunes() []rune Return all mapped code points
Glyph Operations
Method Description
NumGlyphs() int Total number of glyphs
GlyphAt(index int) *Glyph Get glyph by index; returns nil if out of range
SetGlyphAt(index int, g *Glyph) error Replace glyph data at index
AppendGlyph(g *Glyph) (int, error) Append a new glyph, returns its index
CopyGlyph(src, dst int) error Copy glyph data
RemoveGlyphs(indices []int) (remap, error) Remove glyphs at given indices and compact related tables
TranslateGlyph(index, dx, dy int16) error Translate glyph coordinates
ScaleGlyph(index int, sx, sy float64) error Scale glyph coordinates
Glyph Properties
Method Description
IsSimpleGlyph(index int) bool Whether the glyph is a simple glyph
IsCompositeGlyph(index int) bool Whether the glyph is a composite glyph
GlyphBBox(index) (xMin, yMin, xMax, yMax, ok) Glyph bounding box
PointCount(index int) int Number of points in the glyph
ContourCount(index int) int Number of contours in the glyph
Font Metrics
Method Description
UnitsPerEm() uint16 Design units per em
FontBBox() (xMin, yMin, xMax, yMax) Global font bounding box
Ascent() int16 Typographic ascent
Descent() int16 Typographic descent
AdvanceWidth(glyphID uint16) uint16 Advance width for a glyph
AdvanceWidthForRune(r rune) uint16 Advance width for a Unicode code point
LeftSideBearing(glyphID uint16) int16 Left side bearing
SetAdvanceWidth(glyphID, width uint16) error Set advance width
SetLeftSideBearing(glyphID uint16, lsb int16) error Set left side bearing
Font Names
Method Description
FontFamily() string Get font family name
FontFullName() string Get full font name
SetFontFamily(name) Set font family name
SetFontFullName(name) Set full font name
CFF (OpenType/CFF) Support

These methods apply to CFF outline fonts (.otf files). For TrueType outline fonts they return zero values or nil.

Method Description
IsCFF() bool Whether the font uses CFF outlines (OpenType/CFF)
CFFFontName() string CFF font name; empty string for non-CFF fonts
CFFGlyphName(glyphID int) string CFF glyph name; empty string for non-CFF fonts
CFFOutlineAt(index int) *CFFOutline CFF outline by glyph index; nil if out of range or non-CFF
CFFOutlineForRune(r rune) *CFFOutline CFF outline by Unicode code point
Advanced Operations
Method Description
Subset(keepRunes []rune) error Subset the font, keeping only glyphs needed for the specified characters
Text Rendering (font.Face)

Text rendering is provided by the draw subpackage:

import fontdraw "github.com/venusliang/go-font/draw"
Method Description
fontdraw.NewFace(ttf, opts) *Face Create a rendering Face at the specified size
face.Close() error Release resources (currently a no-op)
face.Metrics() font.Metrics Return font metrics (Ascent, Descent, Height, etc.)
face.GlyphAdvance(r rune) (fixed.Int26_6, bool) Return glyph advance width
face.GlyphBounds(r rune) (fixed.Rectangle26_6, fixed.Int26_6, bool) Return glyph bounding box
face.Kern(r0, r1 rune) fixed.Int26_6 Return kerning value between two runes
face.Glyph(dot, r) (dr, mask, maskp, advance, ok) Rasterize a glyph, returning an alpha mask

Supports both TrueType outlines (quadratic Bezier curves) and CFF/OpenType outlines (cubic Bezier curves), using golang.org/x/image/vector.Rasterizer for anti-aliased rendering.

See the draw subpackage README for detailed API documentation and usage examples.

SVG Export

Glyph outline export as standalone SVG documents is provided by the svg subpackage:

import svgexp "github.com/venusliang/go-font/svg"
Function Description
svgexp.Glyph(ttf, glyphIndex, opts) (string, error) Export a glyph by index as a standalone SVG document
svgexp.GlyphForRune(ttf, r, opts) (string, error) Export a glyph by Unicode code point as an SVG document

Supports both TrueType outlines (quadratic Bezier curves) and CFF/OpenType outlines (cubic Bezier curves), using the unified GlyphPath API.

See the svg subpackage README for detailed API documentation and usage examples.

Multi-Format Support

All formats parse to the same TrueTypeFont struct and all editing APIs work regardless of source format.

WOFF (Web Open Font Format)
data, _ := os.ReadFile("myfont.woff")
ttf, _ := gofont.ParseWOFF(data)

// Edit...
ttf.SetFontFamily("NewName")

// Serialize back to WOFF
woffOut, _ := ttf.SerializeWOFF()

// Or convert to TTF / WOFF2
ttfOut, _ := ttf.Serialize()
woff2Out, _ := ttf.SerializeWOFF2()
  • zlib per-table compression
  • Parsed result is equivalent to standard TTF; all editing APIs work
  • Each table is compressed independently during serialization
WOFF2 (Web Open Font Format 2)
data, _ := os.ReadFile("myfont.woff2")
ttf, _ := gofont.ParseWOFF2(data)

// Serialize to WOFF2
woff2Out, _ := ttf.SerializeWOFF2()
  • Brotli single-stream compression (all tables combined)
  • Automatically handles glyf/loca and hmtx transform reversal
  • No table transforms on serialization (transform version 3) for broad compatibility
  • Depends on github.com/andybalholm/brotli (pure Go, no CGO)
EOT (Embedded OpenType)
data, _ := os.ReadFile("myfont.eot")
ttf, _ := gofont.ParseEOT(data)

// Serialize to EOT
eotOut, _ := ttf.SerializeEOT()
  • Microsoft font embedding format, primarily for legacy IE
  • Supports versions 0x00010000 / 0x00020001 / 0x00020002
  • Auto XOR 0x50 decryption
  • EOT metadata (PANOSE, Weight, UnicodeRange, etc.) is auto-populated from OS/2, head, and name tables
  • Name fields use UTF-16LE encoding
TTC (TrueType Collection)
data, _ := os.ReadFile("myfont.ttc")
fonts, _ := gofont.ParseTTC(data)

// Edit the first font
fonts[0].SetFontFamily("NewName")

// Serialize a single font to TTF
ttfOut, _ := fonts[0].Serialize()

// Or re-pack all fonts as TTC
ttcOut, _ := gofont.SerializeTTC(fonts)
  • Multi-font container format (e.g. system CJK fonts like NotoSansCJK.ttc)
  • ParseTTC() returns []TrueTypeFont; each font can be edited and serialized independently
  • Supports TTC versions 1.0 and 2.0
  • Table offsets are automatically adjusted for TTC-relative positioning during serialization
OTF (OpenType/CFF)
data, _ := os.ReadFile("myfont.otf")
ttf, _ := gofont.Parse(data)

if ttf.IsCFF() {
    fmt.Printf("CFF font name: %s\n", ttf.CFFFontName())

    // Get glyph outline
    outline := ttf.CFFOutlineAt(0)
    if outline != nil {
        fmt.Printf("Segments: %d\n", outline.NumSegments())
        for _, seg := range outline.Segments() {
            fmt.Printf("  %v: %v\n", seg.Op, seg.Args)
        }
    }

    // Look up outline by Unicode code point
    outline = ttf.CFFOutlineForRune('A')
}

// Serialize (CFF raw table data is preserved)
out, _ := ttf.Serialize()
os.WriteFile("output.otf", out, 0644)
  • Parse() auto-detects OTF files
  • Parses CFF Header, Name INDEX, Top DICT, String INDEX, Charset, CharStrings INDEX, Private DICT
  • Supports Type 2 CharString outline decoding (moveto/lineto/curveto opcodes, with subroutine calls)
  • CFF raw table data is preserved during serialization for lossless round-trip
Format Limitations
Format Limitation
OTF CFF outlines are read-only and round-trip preserved; modifying CFF CharString data and re-encoding is not supported
WOFF None
WOFF2 No glyf/loca/hmtx table transforms during serialization; compression ratio is slightly lower than official tools
EOT MTX (MicroType Express) compression is not supported; returns an error when encountered
EOT Only TrueType outlines (glyf table) are supported; CFF outlines are not supported
TTC Table sharing is not supported (each font is packed independently, shared tables are not merged)
Format Conversion
// OTF -> TTF (CFF table preserved as-is)
ttf, _ := gofont.Parse(otfData)
ttfOut, _ := ttf.Serialize()

// WOFF2 -> TTF
ttf, _ := gofont.ParseWOFF2(woff2Data)
ttfOut, _ := ttf.Serialize()

// TTF -> EOT
ttf, _ := gofont.Parse(ttfData)
eotOut, _ := ttf.SerializeEOT()

// EOT -> WOFF
ttf, _ := gofont.ParseEOT(eotData)
woffOut, _ := ttf.SerializeWOFF()

// Extract first font from TTC -> WOFF2
fonts, _ := gofont.ParseTTC(ttcData)
woff2Out, _ := fonts[0].SerializeWOFF2()

// Pack multiple fonts into TTC
ttcOut, _ := gofont.SerializeTTC(fonts)

Examples

Remap Unicode

Remap the glyph at code point 0x91 to code point 0xFB:

ttf, _ := gofont.Parse(data)

gid := ttf.RuneToGlyphID(0x91)   // get glyph ID
ttf.RemoveRuneMapping(0x91)       // remove old mapping
ttf.SetRuneMapping(0xFB, gid)     // create new mapping

out, _ := ttf.Serialize()
Query Glyph Info
ttf, _ := gofont.Parse(data)

// Look up glyph by code point
g := ttf.GlyphForRune('A')
if g != nil {
    fmt.Printf("xMin=%d, yMin=%d, xMax=%d, yMax=%d\n",
        g.header.xMin, g.header.yMin,
        g.header.xMax, g.header.yMax)
}

// Enumerate all mappings
for _, m := range ttf.RuneMappings() {
    fmt.Printf("U+%04X -> glyph %d\n", m.Rune, m.GlyphID)
}
Trim Glyphs

Remove unneeded glyphs to reduce font file size:

ttf, _ := gofont.Parse(data)

// Remove glyphs at indices 3, 7, 10
remap, err := ttf.RemoveGlyphs([]int{3, 7, 10})
if err != nil {
    panic(err)
}

// remap tracks old-index -> new-index
// e.g. remap[4] == 3 means old index 4 became new index 3
// Deleted indices do not appear in remap

fmt.Printf("Glyphs after removal: %d\n", ttf.NumGlyphs())

out, _ := ttf.Serialize()

RemoveGlyphs automatically updates:

  • glyf -- removes corresponding glyphs, packs remaining
  • loca -- recalculates offsets
  • hmtx -- removes corresponding horizontal metrics
  • maxp -- updates glyph count and statistics
  • hhea -- updates numberOfHMetrics
  • Composite glyphs -- remaps component references
  • cmap -- updates Unicode-to-glyph-ID mappings

Note: Glyph 0 (.notdef) cannot be removed; it is a required default glyph.

Replace Glyph Data
ttf, _ := gofont.Parse(data)

// Replace glyph at index 1 with a copy of glyph at index 0
src := ttf.GlyphAt(0)
if src != nil {
    newGlyph := &gofont.Glyph{
        header: src.header,
    }
    if src.simpleGlyph != nil {
        sg := *src.simpleGlyph
        newGlyph.simpleGlyph = &sg
    }

    ttf.SetGlyphAt(1, newGlyph)
}

out, _ := ttf.Serialize()
Add Unicode Mappings
ttf, _ := gofont.Parse(data)

// Map 'A' (U+0041) to existing glyph 1
err := ttf.SetRuneMapping('A', 1)
if err != nil {
    panic(err)
}

// Map multiple characters
chars := []rune{'A', 'B', 'C'}
for i, ch := range chars {
    ttf.SetRuneMapping(ch, uint16(i+1))
}

out, _ := ttf.Serialize()
Read Font Info
ttf, _ := gofont.Parse(data)

fmt.Printf("Family: %s\n", ttf.FontFamily())
fmt.Printf("Full name: %s\n", ttf.FontFullName())
fmt.Printf("Units/Em: %d\n", ttf.UnitsPerEm())
fmt.Printf("Ascent: %d, Descent: %d\n", ttf.Ascent(), ttf.Descent())

// Query glyph metrics and properties
w := ttf.AdvanceWidth(1)
lsb := ttf.LeftSideBearing(1)
xMin, yMin, xMax, yMax, _ := ttf.GlyphBBox(1)
pts := ttf.PointCount(1)
fmt.Printf("Glyph 1: width=%d lsb=%d bbox=(%d,%d,%d,%d) points=%d\n",
    w, lsb, xMin, yMin, xMax, yMax, pts)

// Query advance width by Unicode
aw := ttf.AdvanceWidthForRune(0xE001)
fmt.Printf("U+E001 advance width: %d\n", aw)
Font Subsetting
ttf, _ := gofont.Parse(data)

// Keep only the glyphs needed for these characters
err := ttf.Subset([]rune{'A', 'B', 'C', 'D', 'E'})
if err != nil {
    panic(err)
}

fmt.Printf("Glyphs after subsetting: %d\n", ttf.NumGlyphs())

out, _ := ttf.Serialize()
Render Text with font.Drawer
package main

import (
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "os"

    gofont "github.com/venusliang/go-font"
    fontdraw "github.com/venusliang/go-font/draw"

    "golang.org/x/image/font"
    "golang.org/x/image/math/fixed"
)

func main() {
    // Load and parse the font
    data, _ := os.ReadFile("myfont.ttf")
    ttf, _ := gofont.Parse(data)

    // Create a rendering Face at 24pt / 72 DPI
    face := fontdraw.NewFace(&ttf, &fontdraw.FaceOptions{Size: 24, DPI: 72})
    defer face.Close()

    // Create a destination image
    img := image.NewRGBA(image.Rect(0, 0, 400, 60))
    draw.Draw(img, img.Bounds(), image.White, image.Point{}, draw.Src)

    // Draw text using font.Drawer
    d := &font.Drawer{
        Dst:  img,
        Src:  image.Black,
        Face: face,
        Dot:  fixed.P(10, 40),
    }
    d.DrawString("Hello, World")

    // Save as PNG
    f, _ := os.Create("output.png")
    png.Encode(f, img)
    f.Close()
}

Colored text:

// Blue text
blue := image.NewUniform(color.RGBA{0, 0, 255, 255})
d := &font.Drawer{
    Dst:  img,
    Src:  blue,
    Face: face,
    Dot:  fixed.P(10, 40),
}
d.DrawString("Blue text")

Multi-line text:

m := face.Metrics()
lineHeight := m.Height >> 6 // convert to integer pixels

lines := []string{"Line one", "Line two", "Line three"}
for i, line := range lines {
    d.Dot = fixed.P(10, int(m.Ascent>>6)+i*int(lineHeight))
    d.DrawString(line)
}
Modify Font Metrics
ttf, _ := gofont.Parse(data)

// Change advance width of glyph 1
ttf.SetAdvanceWidth(1, 600)
ttf.SetLeftSideBearing(1, 20)

// Change font names
ttf.SetFontFamily("MyFont")
ttf.SetFontFullName("MyFont Regular")

out, _ := ttf.Serialize()
Parse OpenType/CFF Fonts
data, _ := os.ReadFile("myfont.otf")
ttf, _ := gofont.Parse(data)

if ttf.IsCFF() {
    fmt.Printf("CFF font name: %s\n", ttf.CFFFontName())
    fmt.Printf("Glyph count: %d\n", ttf.NumGlyphs())

    // Get glyph name
    name := ttf.CFFGlyphName(1)
    fmt.Printf("Glyph 1 name: %s\n", name)

    // Decode CFF outline
    outline := ttf.CFFOutlineForRune('A')
    if outline != nil {
        fmt.Printf("Segments: %d\n", outline.NumSegments())
        for _, seg := range outline.Segments() {
            switch seg.Op {
            case gofont.CFFOpMoveTo:
                fmt.Printf("  moveto %v\n", seg.Args[:2])
            case gofont.CFFOpLineTo:
                fmt.Printf("  lineto %v\n", seg.Args[:2])
            case gofont.CFFOpCurveTo:
                fmt.Printf("  curveto %v\n", seg.Args[:6])
            }
        }
    }
}

// Serialize (CFF raw table data is fully preserved)
out, _ := ttf.Serialize()
os.WriteFile("output.otf", out, 0644)
Glyph Geometric Transforms
ttf, _ := gofont.Parse(data)

// Translate glyph (right 100 units, down 50 units)
ttf.TranslateGlyph(1, 100, -50)

// Scale glyph (2x in both directions)
ttf.ScaleGlyph(1, 2.0, 2.0)

out, _ := ttf.Serialize()
Append a New Glyph
ttf, _ := gofont.Parse(data)

// Create a new glyph
newGlyph := &gofont.Glyph{
    header: gofont.GlyphHeader{
        numberOfContours: 1,
        xMin: 0, yMin: 0, xMax: 500, yMax: 700,
    },
    simpleGlyph: &gofont.SimpleGlyph{
        endPtsOfContours: []uint16{3},
        xCoordinates:     []int16{0, 500, 500, 0},
        yCoordinates:     []int16{0, 0, 700, 700},
    },
}

idx, _ := ttf.AppendGlyph(newGlyph)
ttf.SetRuneMapping('Z', uint16(idx))

out, _ := ttf.Serialize()

Data Structures

Glyph
type Glyph struct {
    header         GlyphHeader      // contour count, bounding box
    simpleGlyph    *SimpleGlyph     // non-nil for simple glyphs
    compositeGlyph *CompositeGlyph  // non-nil for composite glyphs
}

GlyphHeader

type GlyphHeader struct {
    numberOfContours int16  // >= 0 for simple, < 0 for composite
    xMin, yMin       int16  // bounding box minimum
    xMax, yMax       int16  // bounding box maximum
}

SimpleGlyph

type SimpleGlyph struct {
    endPtsOfContours []uint16  // end point index for each contour
    instructions     []byte    // hinting instructions
    flags            []uint8   // per-point flags
    xCoordinates     []int16   // absolute X coordinates
    yCoordinates     []int16   // absolute Y coordinates
}

CompositeGlyph

type CompositeGlyph struct {
    components []GlyphComponent
}

type GlyphComponent struct {
    flags      uint16     // component flags
    glyphIndex uint16     // referenced glyph index
    arg1, arg2 int16      // positioning arguments
    transform  [4]int16   // optional 2x2 transform matrix (F2Dot14)
}
CFFOutline
type CFFOutline struct {
    // Decoded outline data from CFF Type 2 CharStrings
}

type CFFPathSegment struct {
    Op   CFFPathOp  // CFFOpMoveTo / CFFOpLineTo / CFFOpCurveTo
    Args [6]int32   // Coordinate parameters (first 2 for MoveTo/LineTo, all 6 for CurveTo)
}

const (
    CFFOpMoveTo  CFFPathOp = iota  // Move to new position
    CFFOpLineTo                     // Straight line segment
    CFFOpCurveTo                    // Cubic Bezier curve
)

CFF outlines use cubic Bezier curves (2 control points per curve segment), while TrueType outlines use quadratic Bezier curves.

Supported Font Tables

Table File Description
head head.go Font header, global metrics
hhea hhea.go Horizontal layout header
hmtx hmtx.go Horizontal metrics (advance width + LSB)
maxp maxp.go Maximum profile, glyph count
OS/2 os_2..go OS/2 metrics
name name.go Font name strings
cmap cmap.go Character-to-glyph mapping (formats 0/4/6/12)
loca loca.go Glyph index to offset mapping
glyf glyf.go Glyph outline data
post post.go PostScript name mapping
kern kern.go Kerning table
GPOS gpos.go Glyph positioning table
GSUB gsub.go Glyph substitution table
CFF cff.go Compact Font Format table (OpenType/CFF fonts)
CharString cff_charstring.go CFF Type 2 CharString outline decoding
Rendering draw/face.go font.Face implementation, anti-aliased rasterization via golang.org/x/image/vector
SVG Export svg/svg.go Glyph outline export as standalone SVG documents

Supported Font Formats

Format File Parse Serialize Description
TTF ttf.go / serialize.go Parse() Serialize() TrueType font
OTF ttf.go / cff.go Parse() Serialize() OpenType/CFF font
WOFF woff.go ParseWOFF() SerializeWOFF() zlib per-table compression
WOFF2 woff2.go ParseWOFF2() SerializeWOFF2() Brotli single-stream compression
EOT eot.go ParseEOT() SerializeEOT() Microsoft embedded font
TTC ttc.go ParseTTC() SerializeTTC() TrueType Collection

Running Tests

# Run all tests
go test ./...

# Run a specific test
go test -run TestRemoveGlyphs ./...

# Verbose output
go test -v ./...

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SerializeTTC

func SerializeTTC(fonts []TrueTypeFont) ([]byte, error)

SerializeTTC serializes multiple TrueTypeFont objects into a TTC file.

Types

type BigEndian

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

func (*BigEndian) Append

func (b *BigEndian) Append(bytes []byte)

func (*BigEndian) Bytes

func (b *BigEndian) Bytes(n int) []byte

func (*BigEndian) Fixed16_16

func (b *BigEndian) Fixed16_16() (f Fixed16_16)

func (*BigEndian) I8

func (b *BigEndian) I8() (i8 int8)

func (*BigEndian) I16

func (b *BigEndian) I16() (i16 int16)

func (*BigEndian) I32

func (b *BigEndian) I32() (i32 int32)

func (*BigEndian) I64

func (b *BigEndian) I64() (i64 int64)

func (*BigEndian) Offset

func (b *BigEndian) Offset() int

func (*BigEndian) PutFixed16_16

func (b *BigEndian) PutFixed16_16(f Fixed16_16)

func (*BigEndian) PutU8

func (b *BigEndian) PutU8(u8 uint8)

func (*BigEndian) PutU16

func (b *BigEndian) PutU16(u16 uint16)

func (*BigEndian) PutU32

func (b *BigEndian) PutU32(u32 uint32)

func (*BigEndian) PutU64

func (b *BigEndian) PutU64(u64 uint64)

func (*BigEndian) Read

func (b *BigEndian) Read(n int) []byte

func (*BigEndian) Slice

func (l *BigEndian) Slice(n int) Binary

func (*BigEndian) U8

func (b *BigEndian) U8() (u8 uint8)

func (*BigEndian) U16

func (b *BigEndian) U16() (u16 uint16)

func (*BigEndian) U32

func (b *BigEndian) U32() (u32 uint32)

func (*BigEndian) U64

func (b *BigEndian) U64() (u64 uint64)

type Binary

type Binary interface {
	U8() uint8
	I8() int8
	U16() uint16
	I16() int16
	Fixed16_16() Fixed16_16
	U32() uint32
	I32() int32
	U64() uint64
	I64() int64
	PutU8(uint8)
	PutU16(uint16)
	PutFixed16_16(Fixed16_16)
	PutU32(uint32)
	PutU64(uint64)
	Offset() int
	Bytes(int) []uint8
	Read(int) []uint8
	Slice(int) Binary
	Append([]byte)
}

func BinaryFrom

func BinaryFrom(data []byte, littleEndian bool) Binary

type CFF

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

CFF holds parsed data from a CFF (Compact Font Format) table.

func (*CFF) CharStringData

func (cff *CFF) CharStringData(glyphID int) ([]byte, error)

CharStringData returns the raw charstring data for the given glyph ID.

func (*CFF) DecodeOutlines

func (cff *CFF) DecodeOutlines() ([]*CFFOutline, error)

DecodeOutlines decodes all charstring outlines in the CFF font.

func (*CFF) FontName

func (cff *CFF) FontName() string

FontName returns the font name from the CFF Name INDEX.

func (*CFF) GlyphName

func (cff *CFF) GlyphName(glyphID int) string

GlyphName returns the glyph name for the given glyph ID.

func (*CFF) NumGlyphs

func (cff *CFF) NumGlyphs() int

NumGlyphs returns the number of glyphs from the CharStrings INDEX.

type CFFCharset

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

CFFCharset maps glyph IDs to SIDs.

type CFFHeader

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

CFFHeader is the CFF table header.

type CFFINDEX

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

CFFINDEX represents a CFF INDEX structure. An INDEX stores a count of items, with offsets into a data region. Element i is data[offsets[i]-1 : offsets[i+1]-1] (1-based offsets).

type CFFOutline

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

CFFOutline holds the parsed outline data for a single CFF glyph.

func (*CFFOutline) BBox

func (o *CFFOutline) BBox() (xMin, yMin, xMax, yMax int16)

BBox returns the computed bounding box.

func (*CFFOutline) NumSegments

func (o *CFFOutline) NumSegments() int

NumSegments returns the number of path segments.

func (*CFFOutline) Segments

func (o *CFFOutline) Segments() []CFFPathSegment

Segments returns all path segments.

func (*CFFOutline) Width

func (o *CFFOutline) Width() (width int32, ok bool)

Width returns the glyph width. ok is true if width was specified in charstring.

type CFFPathOp

type CFFPathOp uint8

CFFPathOp represents a path operation in a CFF charstring outline.

const (
	CFFOpMoveTo  CFFPathOp = iota // rmoveto, hmoveto, vmoveto
	CFFOpLineTo                   // rlineto, hlineto, vlineto
	CFFOpCurveTo                  // rrcurveto, hhcurveto, vvcurveto, hvcurveto, vhcurveto
)

type CFFPathSegment

type CFFPathSegment struct {
	Op   CFFPathOp
	Args [6]int32 // relative coordinates; at most 6 for CurveTo
}

CFFPathSegment represents one path drawing segment in a CFF outline.

type CFFPrivateDict

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

CFFPrivateDict holds Private DICT values.

type CFFTopDict

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

CFFTopDict holds key values parsed from the Top DICT.

type CMap

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

type CMapFormat0

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

Format 0: byte encoding table

func (*CMapFormat0) Enumerate

func (f *CMapFormat0) Enumerate(fn func(rune, uint16))

func (*CMapFormat0) Format

func (f *CMapFormat0) Format() uint16

func (*CMapFormat0) Map

func (f *CMapFormat0) Map(r rune) uint16

type CMapFormat4

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

Format 4: segment mapping to delta values

func (*CMapFormat4) Enumerate

func (f *CMapFormat4) Enumerate(fn func(rune, uint16))

func (*CMapFormat4) Format

func (f *CMapFormat4) Format() uint16

func (*CMapFormat4) Map

func (f *CMapFormat4) Map(r rune) uint16

type CMapFormat6

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

Format 6: trimmed table mapping

func (*CMapFormat6) Enumerate

func (f *CMapFormat6) Enumerate(fn func(rune, uint16))

func (*CMapFormat6) Format

func (f *CMapFormat6) Format() uint16

func (*CMapFormat6) Map

func (f *CMapFormat6) Map(r rune) uint16

type CMapFormat12

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

func (*CMapFormat12) Enumerate

func (f *CMapFormat12) Enumerate(fn func(rune, uint16))

func (*CMapFormat12) Format

func (f *CMapFormat12) Format() uint16

func (*CMapFormat12) Map

func (f *CMapFormat12) Map(r rune) uint16

type CMapSubtable

type CMapSubtable interface {
	Format() uint16
	Map(rune) uint16
	Enumerate(func(rune, uint16))
}

type ClassDef

type ClassDef struct {
	Format      uint16             // 1 = sequential, 2 = ranges
	StartGlyph  uint16             // Format 1
	ClassValues []uint16           // Format 1
	Ranges      []ClassRangeRecord // Format 2
}

ClassDef represents a class definition table (format 1 or 2).

type ClassRangeRecord

type ClassRangeRecord struct {
	Start uint16 // startGlyphID
	End   uint16 // endGlyphID
	Class uint16 // classValue
}

ClassRangeRecord represents a range record in ClassDef format 2.

type CompositeGlyph

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

type Coverage

type Coverage struct {
	Format uint16          // 1 = glyph list, 2 = ranges
	Glyphs []uint16        // Format 1
	Ranges []CoverageRange // Format 2
}

Coverage represents a glyph coverage table (format 1 or 2).

type CoverageRange

type CoverageRange struct {
	Start uint16 // startGlyphID
	End   uint16 // endGlyphID
	Index uint16 // startCoverageIndex
}

CoverageRange represents a range record in Coverage format 2.

type Cvt

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

Cvt holds the cvt (Control Value Table) data. It contains an array of FWord (int16) values used by the TrueType interpreter.

type FeatureList

type FeatureList struct {
	Records []FeatureRecord
}

FeatureList represents the list of features in an OpenType Layout table.

type FeatureRecord

type FeatureRecord struct {
	Tag     [4]byte
	Feature FeatureTable
}

FeatureRecord maps a feature tag to its feature table.

type FeatureTable

type FeatureTable struct {
	FeatureParams uint16
	LookupIndices []uint16
}

FeatureTable represents a feature table.

type Fixed2_14

type Fixed2_14 int16

16-bit signed fixed number with the low 14 bits representing fraction.

func (Fixed2_14) Float

func (f Fixed2_14) Float() float64

func (Fixed2_14) String

func (f Fixed2_14) String() string

type Fixed16_16

type Fixed16_16 struct {
	Int  int16
	Frac uint16
}

Fixed is a 16.16 fixed-point number.

func (Fixed16_16) Float

func (f Fixed16_16) Float() float64

func (Fixed16_16) String

func (f Fixed16_16) String() string

type Font

type Font interface {
	Parse([]byte) error
}

Font is an interface for font types that can parse binary data.

type Fpgm

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

Fpgm holds the fpgm (Font Program) table data. This TrueType bytecode is executed once when the font is first loaded.

type GPOS

type GPOS struct {
	MajorVersion uint16
	MinorVersion uint16
	ScriptList   ScriptList
	FeatureList  FeatureList
	LookupList   OTLookupList
}

GPOS represents the Glyph Positioning table.

type GSUB

type GSUB struct {
	MajorVersion uint16
	MinorVersion uint16
	ScriptList   ScriptList
	FeatureList  FeatureList
	LookupList   OTLookupList
}

GSUB represents the Glyph Substitution table.

type Glyph

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

type GlyphComponent

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

type GlyphHeader

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

type GlyphPath

type GlyphPath struct {
	Segments               []PathSegment
	XMin, YMin, XMax, YMax float32
}

GlyphPath holds the outline path data for a single glyph. Coordinates are absolute, in font design units, Y-up.

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

type Hhea

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

type Hmtx

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

type Kern

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

Kern represents the kerning table.

type KernPair

type KernPair struct {
	Left  uint16
	Right uint16
	Value int16
}

KernPair represents a single kerning pair.

type KernSubtable

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

KernSubtable represents a single subtable within the kern table.

type LangSys

type LangSys struct {
	ReqFeatureIndex uint16
	FeatureIndices  []uint16
}

LangSys represents a language system table.

type LangSysRecord

type LangSysRecord struct {
	Tag     [4]byte
	LangSys LangSys
}

LangSysRecord maps a language tag to its LangSys table.

type LangTagRecord

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

type LittleEndian

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

func (*LittleEndian) Append

func (l *LittleEndian) Append(bytes []byte)

func (*LittleEndian) Bytes

func (l *LittleEndian) Bytes(n int) []byte

func (*LittleEndian) Fixed16_16

func (l *LittleEndian) Fixed16_16() (f Fixed16_16)

func (*LittleEndian) I8

func (l *LittleEndian) I8() (i8 int8)

func (*LittleEndian) I16

func (l *LittleEndian) I16() (i16 int16)

func (*LittleEndian) I32

func (l *LittleEndian) I32() (i32 int32)

func (*LittleEndian) I64

func (l *LittleEndian) I64() (i64 int64)

func (*LittleEndian) Offset

func (l *LittleEndian) Offset() int

func (*LittleEndian) PutFixed16_16

func (l *LittleEndian) PutFixed16_16(f Fixed16_16)

func (*LittleEndian) PutU8

func (l *LittleEndian) PutU8(u8 uint8)

func (*LittleEndian) PutU16

func (l *LittleEndian) PutU16(u16 uint16)

func (*LittleEndian) PutU32

func (l *LittleEndian) PutU32(u32 uint32)

func (*LittleEndian) PutU64

func (l *LittleEndian) PutU64(u64 uint64)

func (*LittleEndian) Read

func (l *LittleEndian) Read(n int) []byte

func (*LittleEndian) Slice

func (l *LittleEndian) Slice(n int) Binary

func (*LittleEndian) U8

func (l *LittleEndian) U8() (u8 uint8)

func (*LittleEndian) U16

func (l *LittleEndian) U16() (u16 uint16)

func (*LittleEndian) U32

func (l *LittleEndian) U32() (u32 uint32)

func (*LittleEndian) U64

func (l *LittleEndian) U64() (u64 uint64)

type Loca

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

type LongHorMetric

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

type MacStyle

type MacStyle uint8
const (
	MacStyleBold      MacStyle = 1 << iota // 0x0001
	MacStyleItalic                         // 0x0002
	MacStyleUnderline                      // 0x0004
	MacStyleOutline                        // 0x0008
	MacStyleShadow                         // 0x0010
	MacStyleCondensed                      // 0x0020
	MacStyleExtended                       // 0x0040
)

type Maxp

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

type Name

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

type NameRecord

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

type OS2

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

type OTLookup

type OTLookup struct {
	LookupType       uint16
	LookupFlag       uint16
	MarkFilteringSet uint16
	SubTables        [][]byte // raw subtable data
}

OTLookup represents a single lookup table.

type OTLookupList

type OTLookupList struct {
	Lookups []OTLookup
}

OTLookupList represents the list of lookups in an OpenType Layout table.

type PathOp

type PathOp uint8

PathOp represents a path drawing operation.

const (
	OpMoveTo PathOp = iota // move to (Args[0], Args[1])
	OpLineTo               // line to (Args[0], Args[1])
	OpQuadTo               // quadratic Bézier: control at (Args[0], Args[1]), end at (Args[2], Args[3])
	OpCubeTo               // cubic Bézier: ctrl1 (Args[0], Args[1]), ctrl2 (Args[2], Args[3]), end (Args[4], Args[5])
)

type PathSegment

type PathSegment struct {
	Op   PathOp
	Args [6]float32
}

PathSegment represents one path drawing command with absolute coordinates in font design units (Y-axis points up, per OpenType convention).

type Post

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

type Prep

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

Prep holds the prep (Control Value Program) table data. This TrueType bytecode is executed whenever the font size or transformation changes.

type ScriptList

type ScriptList struct {
	Records []ScriptRecord
}

ScriptList represents the list of scripts in an OpenType Layout table.

type ScriptRecord

type ScriptRecord struct {
	Tag    [4]byte
	Script ScriptTable
}

ScriptRecord maps a script tag to its script table.

type ScriptTable

type ScriptTable struct {
	DefaultLangSys *LangSys
	LangSysRecords []LangSysRecord
}

ScriptTable represents a script table with optional default LangSys and language-specific records.

type SequentialMapGroup

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

Format 12: segmented coverage (32-bit)

type SimpleGlyph

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

type Table

type Table interface {
	Read([]byte) error
	Write() []byte
}

type TableDirectory

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

type TrueTypeFont

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

func Parse

func Parse(data []byte) (TrueTypeFont, error)

Parse parses TTF binary data and returns a TrueTypeFont.

func ParseEOT

func ParseEOT(data []byte) (TrueTypeFont, error)

ParseEOT parses an EOT (Embedded OpenType) file and returns a TrueTypeFont.

func ParseTTC

func ParseTTC(data []byte) ([]TrueTypeFont, error)

ParseTTC parses a TTC (TrueType Collection) file and returns all fonts within it.

func ParseWOFF

func ParseWOFF(data []byte) (TrueTypeFont, error)

ParseWOFF parses a WOFF (Web Open Font Format) file and returns a TrueTypeFont. It decompresses the WOFF table data and delegates to the standard TTF parser.

func ParseWOFF2

func ParseWOFF2(data []byte) (TrueTypeFont, error)

ParseWOFF2 parses a WOFF2 (Web Open Font Format 2) file and returns a TrueTypeFont.

func (*TrueTypeFont) AdvanceWidth

func (ttf *TrueTypeFont) AdvanceWidth(glyphID uint16) uint16

AdvanceWidth returns the advance width for the given glyph ID.

func (*TrueTypeFont) AdvanceWidthForRune

func (ttf *TrueTypeFont) AdvanceWidthForRune(r rune) uint16

AdvanceWidthForRune returns the advance width for the glyph mapped to the given rune.

func (*TrueTypeFont) AppendGlyph

func (ttf *TrueTypeFont) AppendGlyph(g *Glyph) (int, error)

AppendGlyph adds a new glyph to the font and returns its index.

func (*TrueTypeFont) Ascent

func (ttf *TrueTypeFont) Ascent() int16

Ascent returns the font ascent value from hhea table.

func (*TrueTypeFont) CFFFontName

func (ttf *TrueTypeFont) CFFFontName() string

CFFFontName returns the CFF font name. Returns "" for non-CFF fonts.

func (*TrueTypeFont) CFFGlyphName

func (ttf *TrueTypeFont) CFFGlyphName(glyphID int) string

CFFGlyphName returns the glyph name for the given glyph ID. Works for both CFF (via charset) and TrueType (via post table) fonts.

func (*TrueTypeFont) CFFOutlineAt

func (ttf *TrueTypeFont) CFFOutlineAt(index int) *CFFOutline

CFFOutlineAt decodes and returns the CFF outline for the glyph at index. Returns nil for non-CFF fonts or out-of-range indices.

func (*TrueTypeFont) CFFOutlineForRune

func (ttf *TrueTypeFont) CFFOutlineForRune(r rune) *CFFOutline

CFFOutlineForRune decodes and returns the CFF outline for the glyph mapped to r. Returns nil for non-CFF fonts or unmapped runes.

func (*TrueTypeFont) CapHeight

func (ttf *TrueTypeFont) CapHeight() int16

CapHeight returns the cap height from OS/2 table.

func (*TrueTypeFont) CaretSlope

func (ttf *TrueTypeFont) CaretSlope() (run, rise int16)

CaretSlope returns the caret slope (run, rise) from hhea table.

func (*TrueTypeFont) ContourCount

func (ttf *TrueTypeFont) ContourCount(index int) int

ContourCount returns the number of contours in the glyph at index. Returns 0 for composite glyphs or out-of-range indices.

func (*TrueTypeFont) CopyGlyph

func (ttf *TrueTypeFont) CopyGlyph(srcIndex, dstIndex int) error

CopyGlyph copies the glyph data from srcIndex to dstIndex.

func (*TrueTypeFont) Descent

func (ttf *TrueTypeFont) Descent() int16

Descent returns the font descent value from hhea table.

func (*TrueTypeFont) FontBBox

func (ttf *TrueTypeFont) FontBBox() (xMin, yMin, xMax, yMax int16)

FontBBox returns the global font bounding box (min/max across all glyphs).

func (*TrueTypeFont) FontFamily

func (ttf *TrueTypeFont) FontFamily() string

FontFamily returns the font family name (nameID 1).

func (*TrueTypeFont) FontFullName

func (ttf *TrueTypeFont) FontFullName() string

FontFullName returns the full font name (nameID 4).

func (*TrueTypeFont) GlyphAt

func (ttf *TrueTypeFont) GlyphAt(index int) *Glyph

GlyphAt returns the glyph at the given index, or nil if out of range.

func (*TrueTypeFont) GlyphBBox

func (ttf *TrueTypeFont) GlyphBBox(index int) (xMin, yMin, xMax, yMax int16, ok bool)

GlyphBBox returns the bounding box of the glyph at index. Returns ok=false if the index is out of range.

func (*TrueTypeFont) GlyphForRune

func (ttf *TrueTypeFont) GlyphForRune(r rune) *Glyph

GlyphForRune returns the glyph data for a Unicode code point, or nil if not mapped.

func (*TrueTypeFont) GlyphPath

func (f *TrueTypeFont) GlyphPath(glyphIndex int) (*GlyphPath, error)

GlyphPath returns the outline path for the glyph at the given index. Works for both TrueType (quadratic beziers) and CFF/OpenType (cubic beziers) fonts. Returns an empty path (no segments) for glyphs with no outline (e.g. space, .notdef).

func (*TrueTypeFont) IsCFF

func (ttf *TrueTypeFont) IsCFF() bool

IsCFF reports whether the font uses CFF outlines (OpenType/CFF, version "OTTO").

func (*TrueTypeFont) IsCompositeGlyph

func (ttf *TrueTypeFont) IsCompositeGlyph(index int) bool

IsCompositeGlyph reports whether the glyph at index is a composite glyph.

func (*TrueTypeFont) IsSimpleGlyph

func (ttf *TrueTypeFont) IsSimpleGlyph(index int) bool

IsSimpleGlyph reports whether the glyph at index is a simple glyph.

func (*TrueTypeFont) KernPair

func (ttf *TrueTypeFont) KernPair(left, right uint16) int16

KernPair returns the kerning value between two glyph IDs. Returns 0 if no kerning pair exists or the kern table is not present.

func (*TrueTypeFont) LeftSideBearing

func (ttf *TrueTypeFont) LeftSideBearing(glyphID uint16) int16

LeftSideBearing returns the left side bearing for the given glyph ID.

func (*TrueTypeFont) LineGap

func (ttf *TrueTypeFont) LineGap() int16

LineGap returns the font line gap value from hhea table.

func (*TrueTypeFont) MappedRunes

func (ttf *TrueTypeFont) MappedRunes() []rune

MappedRunes returns all Unicode code points that have a glyph mapping.

func (*TrueTypeFont) NumGlyphs

func (ttf *TrueTypeFont) NumGlyphs() int

NumGlyphs returns the number of glyphs in the font.

func (*TrueTypeFont) PointCount

func (ttf *TrueTypeFont) PointCount(index int) int

PointCount returns the number of points in the glyph at index. Returns 0 for composite glyphs or out-of-range indices.

func (*TrueTypeFont) RemoveGlyphs

func (ttf *TrueTypeFont) RemoveGlyphs(indices []int) (remap map[int]int, err error)

RemoveGlyphs removes glyphs at the given indices and compacts all related tables. Returns a remap table: old index → new index. Indices not in the map were removed. Glyph 0 (.notdef) cannot be removed.

func (*TrueTypeFont) RemoveRuneMapping

func (ttf *TrueTypeFont) RemoveRuneMapping(r rune)

RemoveRuneMapping removes the mapping for a Unicode code point.

func (*TrueTypeFont) RuneMappings

func (ttf *TrueTypeFont) RuneMappings() []struct {
	Rune    rune
	GlyphID uint16
}

RuneMappings returns all rune-to-glyph mappings sorted by rune value.

func (*TrueTypeFont) RuneToGlyphID

func (ttf *TrueTypeFont) RuneToGlyphID(r rune) uint16

RuneToGlyphID returns the glyph ID for a Unicode code point, or 0 if not mapped.

func (*TrueTypeFont) ScaleGlyph

func (ttf *TrueTypeFont) ScaleGlyph(index int, sx, sy float64) error

ScaleGlyph scales all coordinates of the glyph at index by factors sx and sy. Coordinates are rounded to nearest integer after scaling.

func (*TrueTypeFont) Serialize

func (ttf *TrueTypeFont) Serialize() ([]byte, error)

func (*TrueTypeFont) SerializeEOT

func (ttf *TrueTypeFont) SerializeEOT() ([]byte, error)

SerializeEOT serializes the font as an EOT (Embedded OpenType) file.

func (*TrueTypeFont) SerializeWOFF

func (ttf *TrueTypeFont) SerializeWOFF() ([]byte, error)

SerializeWOFF serializes the font as a WOFF (Web Open Font Format) file.

func (*TrueTypeFont) SerializeWOFF2

func (ttf *TrueTypeFont) SerializeWOFF2() ([]byte, error)

SerializeWOFF2 serializes the font as a WOFF2 file. No table transforms are applied (all tables stored raw).

func (*TrueTypeFont) SetAdvanceWidth

func (ttf *TrueTypeFont) SetAdvanceWidth(glyphID uint16, width uint16) error

SetAdvanceWidth sets the advance width for the given glyph ID.

func (*TrueTypeFont) SetFontFamily

func (ttf *TrueTypeFont) SetFontFamily(name string)

SetFontFamily sets the font family name (nameID 1).

func (*TrueTypeFont) SetFontFullName

func (ttf *TrueTypeFont) SetFontFullName(name string)

SetFontFullName sets the full font name (nameID 4).

func (*TrueTypeFont) SetGlyphAt

func (ttf *TrueTypeFont) SetGlyphAt(index int, g *Glyph) error

SetGlyphAt replaces the glyph data at the given index. Returns an error if the index is out of range.

func (*TrueTypeFont) SetLeftSideBearing

func (ttf *TrueTypeFont) SetLeftSideBearing(glyphID uint16, lsb int16) error

SetLeftSideBearing sets the left side bearing for the given glyph ID.

func (*TrueTypeFont) SetRuneMapping

func (ttf *TrueTypeFont) SetRuneMapping(r rune, glyphID uint16) error

SetRuneMapping maps a Unicode code point to the given glyph ID. Returns an error if glyphID is out of range.

func (*TrueTypeFont) SetRuneMappings

func (ttf *TrueTypeFont) SetRuneMappings(mappings map[rune]uint16) error

SetRuneMappings sets multiple rune-to-glyph mappings at once.

func (*TrueTypeFont) Subset

func (ttf *TrueTypeFont) Subset(keepRunes []rune) error

Subset removes all glyphs that are not needed by the specified runes. Glyph 0 (.notdef) is always kept. Glyphs not referenced by any rune in keepRunes are removed. Composite glyph dependencies are automatically preserved.

func (*TrueTypeFont) TranslateGlyph

func (ttf *TrueTypeFont) TranslateGlyph(index int, dx, dy int16) error

TranslateGlyph shifts all coordinates of the glyph at index by (dx, dy).

func (*TrueTypeFont) UnitsPerEm

func (ttf *TrueTypeFont) UnitsPerEm() uint16

UnitsPerEm returns the font's units per em value (design space size).

func (*TrueTypeFont) XHeight

func (ttf *TrueTypeFont) XHeight() int16

XHeight returns the x-height from OS/2 table.

Directories

Path Synopsis
Package svg provides SVG document export for font glyph outlines using the unified GlyphPath API.
Package svg provides SVG document export for font glyph outlines using the unified GlyphPath API.

Jump to

Keyboard shortcuts

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