forked from Techbinator/go-table-image
/
basic.go
146 lines (130 loc) · 2.58 KB
/
basic.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package tableimage
import (
"image"
"image/draw"
"golang.org/x/image/font"
"golang.org/x/image/font/basicfont"
"golang.org/x/image/math/fixed"
)
func (ti *tableImage) setRgba() {
img := image.NewRGBA(image.Rect(0, 0, ti.width, ti.height))
//set image background
draw.Draw(img, img.Bounds(), &image.Uniform{getColorByHex(ti.backgroundColor)}, image.Point{}, draw.Src)
ti.img = img
}
func (ti *tableImage) addString(x, y int, label string, color string) {
point := fixed.Point26_6{X: fixed.Int26_6(x * 64), Y: fixed.Int26_6(y * 64)}
d := &font.Drawer{
Dst: ti.img,
Src: image.NewUniform(getColorByHex(color)),
Face: basicfont.Face7x13,
Dot: point,
}
d.DrawString(label)
}
// Thx to https://github.com/StephaneBunel/bresenham
func (ti *tableImage) addLine(x1, y1, x2, y2 int, color string) {
var dx, dy, e, slope int
col := getColorByHex(color)
// Because drawing p1 -> p2 is equivalent to draw p2 -> p1,
// I sort points in x-axis order to handle only half of possible cases.
if x1 > x2 {
x1, y1, x2, y2 = x2, y2, x1, y1
}
dx, dy = x2-x1, y2-y1
// Because point is x-axis ordered, dx cannot be negative
if dy < 0 {
dy = -dy
}
switch {
// Is line a point ?
case x1 == x2 && y1 == y2:
ti.img.Set(x1, y1, col)
// Is line an horizontal ?
case y1 == y2:
for ; dx != 0; dx-- {
ti.img.Set(x1, y1, col)
x1++
}
ti.img.Set(x1, y1, col)
// Is line a vertical ?
case x1 == x2:
if y1 > y2 {
y1, y2 = y2, y1
_ = y2
}
for ; dy != 0; dy-- {
ti.img.Set(x1, y1, col)
y1++
}
ti.img.Set(x1, y1, col)
// Is line a diagonal ?
case dx == dy:
if y1 < y2 {
for ; dx != 0; dx-- {
ti.img.Set(x1, y1, col)
x1++
y1++
}
} else {
for ; dx != 0; dx-- {
ti.img.Set(x1, y1, col)
x1++
y1--
}
}
ti.img.Set(x1, y1, col)
// wider than high ?
case dx > dy:
if y1 < y2 {
dy, e, slope = 2*dy, dx, 2*dx
for ; dx != 0; dx-- {
ti.img.Set(x1, y1, col)
x1++
e -= dy
if e < 0 {
y1++
e += slope
}
}
} else {
dy, e, slope = 2*dy, dx, 2*dx
for ; dx != 0; dx-- {
ti.img.Set(x1, y1, col)
x1++
e -= dy
if e < 0 {
y1--
e += slope
}
}
}
ti.img.Set(x2, y2, col)
// higher than wide.
default:
if y1 < y2 {
dx, e, slope = 2*dx, dy, 2*dy
for ; dy != 0; dy-- {
ti.img.Set(x1, y1, col)
y1++
e -= dx
if e < 0 {
x1++
e += slope
}
}
} else {
dx, e, slope = 2*dx, dy, 2*dy
for ; dy != 0; dy-- {
ti.img.Set(x1, y1, col)
y1--
e -= dx
if e < 0 {
x1++
e += slope
}
}
}
ti.img.Set(x2, y2, col)
}
}