-
Notifications
You must be signed in to change notification settings - Fork 0
/
charts.go
60 lines (53 loc) · 1.13 KB
/
charts.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
package charts
import (
"image"
"image/png"
"os"
)
const (
// BarWidth is the width of the chart bars
BarWidth = 50
// SepWidth is the width of the seperator between the chart bars
SepWidth = 10
// BarHeightCoeff is the coefficient to use to multiply the chart bar heights
BarHeightCoeff = 2
)
// Drawer draws the charts using different techniques
type Drawer interface {
Draw(w, h int, data []int) image.Image
}
// Draw charts using standard image package
func Draw(drawer Drawer, filename string, data []int) error {
w := computeMaxWidth(data)
h := computeMaxHeight(data)
img := drawer.Draw(w, h, data)
return writeToFile(filename, img)
}
func computeMaxHeight(data []int) int {
max := 0
for _, d := range data {
if max < d {
max = d
}
}
return max * BarHeightCoeff
}
func computeMaxWidth(data []int) int {
if len(data) == 0 {
return 0
}
nbSep := len(data) - 1
if len(data) < 1 {
nbSep = 0
}
return BarWidth*len(data) + SepWidth*nbSep
}
func writeToFile(filename string, img image.Image) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
err = png.Encode(f, img)
return nil
}