-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpie.go
110 lines (92 loc) · 2.54 KB
/
pie.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
package gopie
import (
"fmt"
"math"
)
type pie struct {
Slices *[]slice
Circle *circle
Background *circle
}
func newPie(chart PieChart, pieRect rectangle, uid string) pie {
if len(chart.Values) == 0 {
return emptyPie(chart, pieRect, uid)
}
if len(chart.Values) == 1 {
return uncutPie(chart, pieRect, uid)
}
return cutPie(chart, pieRect, uid)
}
func emptyPie(chart PieChart, pieRect rectangle, uid string) pie {
return pie{}
}
func uncutPie(chart PieChart, pieRect rectangle, uid string) pie {
centerX, centerY := pieRect.getCenter()
slicesCircleRadius := calculateSlicesRadius(chart, pieRect)
return pie{
Circle: &circle{
CenterX: centerX,
CenterY: centerY,
Radius: slicesCircleRadius,
Style: createSliceStyle(chart, 0),
ChartID: uid,
},
Background: createBackgroundCircle(chart, pieRect),
}
}
func cutPie(chart PieChart, pieRect rectangle, uid string) pie {
centerX, centerY := pieRect.getCenter()
radius := calculateSlicesRadius(chart, pieRect)
sum := float64(0)
total := chart.calculateTotalValue()
slices := make([]slice, len(chart.Values))
for index, value := range chart.Values {
angleOffset := (sum / total) * twoPi
slices[index] = createPieSlice(uid, index, total, angleOffset, value, centerX, centerY, radius, chart)
sum += value.Value
}
return pie{
Slices: &slices,
Background: createBackgroundCircle(chart, pieRect),
}
}
func createPieSlice(chartID string, id int, total, angleOffset float64, value Value, centerX, centerY, radius float64, chart PieChart) slice {
angle := twoPi * value.Value / total
startX, startY := toDecartTranslate(angleOffset, radius, centerX, centerY)
endX, endY := toDecartTranslate(angleOffset+angle, radius, centerX, centerY)
lineSweep := 0
if angle > math.Pi {
lineSweep = 1
}
path := fmt.Sprintf(
"M %v %v L %v %v A %v %v 0 %v 1 %v %v Z",
centerX, centerY,
startX, startY,
radius, radius,
lineSweep,
endX, endY)
return slice{
ChartID: chartID,
ID: id,
Path: path,
Style: createSliceStyle(chart, id),
}
}
func createBackgroundCircle(chart PieChart, pieRect rectangle) *circle {
centerX, centerY := pieRect.getCenter()
radius := pieRect.calculateIncircleRadius()
return &circle{
CenterX: centerX,
CenterY: centerY,
Radius: radius,
Style: createBackgroundCircleStyle(chart),
}
}
func calculateSlicesRadius(c PieChart, r rectangle) float64 {
outerRadius := r.calculateIncircleRadius()
strokeWidth := c.getStrokeWidth()
if strokeWidth == 0 {
return outerRadius
}
return outerRadius - float64(strokeWidth)/2
}