-
Notifications
You must be signed in to change notification settings - Fork 0
/
ttf.go
70 lines (58 loc) · 1.71 KB
/
ttf.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package tigrfont
import (
"fmt"
"image"
xfont "golang.org/x/image/font"
"golang.org/x/image/font/opentype"
)
func tigrFromTTF(options Options, ttfBytes []byte, runeSet []rune, mode missingGlyphMode, watermark bool) (*image.NRGBA, int, error) {
font, err := opentype.Parse(ttfBytes)
if err != nil {
return nil, 0, fmt.Errorf("failed to parse TTF: %w", err)
}
if options.MeasureX {
options.Measure = "X"
}
if len(options.Measure) > 0 {
measure := []rune(options.Measure)[0]
options.FontSize, err = getPointSizeFrom(font, options.FontSize, measure)
if err != nil {
return nil, 0, fmt.Errorf("failed to measure char %q: %w", measure, err)
}
}
face, err := opentype.NewFace(font, &opentype.FaceOptions{
DPI: float64(options.DPI),
Size: float64(options.FontSize),
Hinting: xfont.HintingFull,
})
if err != nil {
return nil, 0, fmt.Errorf("failed to create font face: %w", err)
}
image, rendered, err := renderFontSheet(runeSet, face, mode, watermark)
if err != nil {
return nil, 0, fmt.Errorf("failed to render TTF: %w", err)
}
return image, rendered, nil
}
func getPointSizeFrom(font *opentype.Font, fontSize int, char rune) (int, error) {
face, err := opentype.NewFace(
font,
&opentype.FaceOptions{
DPI: 72.0, Size: float64(fontSize), Hinting: xfont.HintingFull,
})
if err != nil {
return 0, err
}
img, rendered, err := renderFontSheet([]rune{char}, face, removeMissing, false)
if rendered == 0 {
return 0, fmt.Errorf("cannot measure non-existant char %q", string(char))
}
if err != nil {
return 0, err
}
bounds := contentBounds(img)
actual := float64(bounds.Dy())
expected := float64(fontSize)
factor := expected / actual
return int(expected * factor), nil
}