-
Notifications
You must be signed in to change notification settings - Fork 38
/
draw.go
81 lines (68 loc) · 1.53 KB
/
draw.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
71
72
73
74
75
76
77
78
79
80
81
package avatar
import (
"image"
"image/color"
"image/draw"
"io/ioutil"
"math"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
)
// drawer draws an image.Image
type drawer struct {
fontSize float64
dpi float64
fontHinting font.Hinting
face font.Face
}
func newDrawer(fontFile string) *drawer {
if fontFile == "" {
panic("fontFile must be specific font path")
}
g := new(drawer)
g.fontSize = 75.0
g.dpi = 72.0
g.fontHinting = font.HintingNone
ttf, err := getTTF(fontFile)
if err != nil {
panic(err)
}
g.face = truetype.NewFace(ttf, &truetype.Options{
Size: g.fontSize,
DPI: g.dpi,
Hinting: g.fontHinting,
})
return g
}
// our avatar image is square
func (g *drawer) Draw(s string, size int, bg *color.RGBA) image.Image {
// draw the background
dst := image.NewRGBA(image.Rect(0, 0, size, size))
draw.Draw(dst, dst.Bounds(), &image.Uniform{bg}, image.ZP, draw.Src)
// draw the text
drawer := &font.Drawer{
Dst: dst,
Src: image.White,
Face: g.face,
}
y := 10 + int(math.Ceil(g.fontSize*g.dpi/72)) //FIXME: what does it mean?
drawer.Dot = fixed.Point26_6{
X: (fixed.I(size) - drawer.MeasureString(s)) / 2,
Y: fixed.I(y),
}
drawer.DrawString(s)
return dst
}
// read the font file as *truetype.Font
func getTTF(fontFile string) (*truetype.Font, error) {
fontBytes, err := ioutil.ReadFile(fontFile)
if err != nil {
return nil, err
}
ttf, err := truetype.Parse(fontBytes)
if err != nil {
return nil, err
}
return ttf, nil
}