Skip to content

Commit f9531a3

Browse files
committed
Add a face.Metrics method, and parse hhea ascent and descent.
A recent change added a Metrics method to the font.Face interface.
1 parent 9ce4eec commit f9531a3

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

example/truetype/main.go

+8
Original file line numberDiff line numberDiff line change
@@ -77,4 +77,12 @@ func main() {
7777
printGlyph(g)
7878
i1 := f.Index(c1)
7979
fmt.Printf("\n'%c', '%c' Kern:%d\n", c0, c1, f.Kern(fupe, i0, i1))
80+
81+
fmt.Printf("\nThe numbers above are in FUnits.\n" +
82+
"The numbers below are in 26.6 fixed point pixels, at 12pt and 72dpi.\n\n")
83+
a := truetype.NewFace(f, &truetype.Options{
84+
Size: 12,
85+
DPI: 72,
86+
})
87+
fmt.Printf("%#v\n", a.Metrics())
8088
}

truetype/face.go

+12
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package truetype
77

88
import (
99
"image"
10+
"math"
1011

1112
"github.com/golang/freetype/raster"
1213
"golang.org/x/image/font"
@@ -249,6 +250,17 @@ func (a *face) index(r rune) Index {
249250
// Close satisfies the font.Face interface.
250251
func (a *face) Close() error { return nil }
251252

253+
// Metrics satisfies the font.Face interface.
254+
func (a *face) Metrics() font.Metrics {
255+
scale := float64(a.scale)
256+
fupe := float64(a.f.FUnitsPerEm())
257+
return font.Metrics{
258+
Height: a.scale,
259+
Ascent: fixed.Int26_6(math.Ceil(scale * float64(+a.f.ascent) / fupe)),
260+
Descent: fixed.Int26_6(math.Ceil(scale * float64(-a.f.descent) / fupe)),
261+
}
262+
}
263+
252264
// Kern satisfies the font.Face interface.
253265
func (a *face) Kern(r0, r1 rune) fixed.Int26_6 {
254266
i0 := a.index(r0)

truetype/truetype.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,9 @@ type Font struct {
184184
locaOffsetFormat int
185185
nGlyph, nHMetric, nKern int
186186
fUnitsPerEm int32
187-
bounds fixed.Rectangle26_6
187+
ascent int32 // In FUnits.
188+
descent int32 // In FUnits; typically negative.
189+
bounds fixed.Rectangle26_6 // In FUnits.
188190
// Values from the maxp section.
189191
maxTwilightPoints, maxStorage, maxFunctionDefs, maxStackElements uint16
190192
}
@@ -289,6 +291,8 @@ func (f *Font) parseHhea() error {
289291
if len(f.hhea) != 36 {
290292
return FormatError(fmt.Sprintf("bad hhea length: %d", len(f.hhea)))
291293
}
294+
f.ascent = int32(int16(u16(f.hhea, 4)))
295+
f.descent = int32(int16(u16(f.hhea, 6)))
292296
f.nHMetric = int(u16(f.hhea, 34))
293297
if 4*f.nHMetric+2*(f.nGlyph-f.nHMetric) != len(f.hmtx) {
294298
return FormatError(fmt.Sprintf("bad hmtx length: %d", len(f.hmtx)))

0 commit comments

Comments
 (0)