-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
font.go
40 lines (34 loc) · 1.04 KB
/
font.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Some of this code (namely the code for computing the
// width of a string in a given font) was copied from
// code.google.com/p/freetype-go/freetype/ which includes
// the following copyright notice:
// Copyright 2010 The Freetype-Go Authors. All rights reserved.
package main
import (
"github.com/golang/freetype/truetype"
"github.com/pkg/errors"
"golang.org/x/image/math/fixed"
)
const (
fontSize = 11
)
func calculateTextWidth(text string) (int, error) {
binFont, _ := assets.ReadFile("assets/DejaVuSans.ttf")
font, err := truetype.Parse(binFont)
if err != nil {
return 0, errors.Wrap(err, "parsing truetype font")
}
scale := fontSize / float64(font.FUnitsPerEm())
width := 0
prev, hasPrev := truetype.Index(0), false
for _, rune := range text {
fUnitsPerEm := fixed.Int26_6(font.FUnitsPerEm())
index := font.Index(rune)
if hasPrev {
width += int(font.Kern(fUnitsPerEm, prev, index))
}
width += int(font.HMetric(fUnitsPerEm, index).AdvanceWidth)
prev, hasPrev = index, true
}
return int(float64(width) * scale), nil
}