-
Notifications
You must be signed in to change notification settings - Fork 0
/
pngWriter.go
81 lines (70 loc) · 1.68 KB
/
pngWriter.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 weather2png_server
import (
"image"
"image/color"
"image/png"
"io"
"io/ioutil"
"log"
"sync"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
)
type PngWriter struct {
cxt *freetype.Context
width int
height int
img *image.Gray
//fgColor *image.Uniform
//timeSize int
//dateSize int
//prefixSize int
//infoSize int
}
var fontLoadOnce = sync.Once{}
var font *truetype.Font
func NewPngWriter(w, h int, fontPath string) *PngWriter {
if font == nil {
fontLoadOnce.Do(func() {
if font == nil {
fontData, err := ioutil.ReadFile(fontPath)
if err != nil {
panic(err)
}
font, err = truetype.Parse(fontData)
}
})
}
img := image.NewGray(image.Rectangle{image.Point{0, 0}, image.Point{w, h}})
for i, _ := range img.Pix {
img.Pix[i] = 0xff
}
freetypeCxt := freetype.NewContext()
freetypeCxt.SetDst(img)
freetypeCxt.SetSrc(image.NewUniform(color.Black))
freetypeCxt.SetFont(font)
freetypeCxt.SetClip(img.Bounds())
return &PngWriter{freetypeCxt, w, h, img} //, 80, 40, 24, 40}
}
func (thiz *PngWriter) Reset(writer io.Writer) {
img := image.NewGray(image.Rectangle{image.Point{0, 0}, image.Point{thiz.width, thiz.height}})
for i, _ := range img.Pix {
img.Pix[i] = 0xff
}
thiz.cxt.SetDst(img)
png.Encode(writer, thiz.img)
thiz.img = img
}
func (thiz *PngWriter) VerticalLine(x1, y, x2 int) {
for x := x1; x < x2; x++ {
thiz.img.Set(x, y, color.Black)
thiz.img.Set(x, y+1, color.Black)
}
}
func (thiz *PngWriter) Text(txt string, x, y int, size float64) {
thiz.cxt.SetFontSize(size)
_, err := thiz.cxt.DrawString(txt, freetype.Pt(x, y))
if err != nil {
log.Println("ERRO: PngWriter draw string failed", err)
}
}