-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
108 lines (90 loc) · 1.84 KB
/
util.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
package txtp
import (
"fmt"
"strings"
"unicode"
)
func parseHexColor(s string) (r, g, b, a uint8) {
s = strings.TrimPrefix(strings.ToLower(s), "#")
a = 255
if len(s) == 3 {
format := "%1x%1x%1x"
fmt.Sscanf(s, format, &r, &g, &b)
r |= r << 4
g |= g << 4
b |= b << 4
return
}
if len(s) == 6 {
format := "%02x%02x%02x"
fmt.Sscanf(s, format, &r, &g, &b)
return
}
if len(s) == 8 {
format := "%02x%02x%02x%02x"
fmt.Sscanf(s, format, &r, &g, &b, &a)
return
}
return
}
func breakWords(s string) []string {
s = strings.TrimSpace(s)
results := []string{}
word := []rune{}
for i, r := range s {
// Space
if i > 0 && r != ' ' && s[i-1] == ' ' {
// push word into results & clear word
results = append(results, string(word))
word = []rune{r}
continue
}
// Han
if unicode.In(r, unicode.Han) {
// break left
if len(word) > 0 {
// push 字 into results & clear word
results = append(results, string(word))
word = []rune{}
}
word = append(word, r)
continue
}
if unicode.In(r, unicode.Latin) && len(word) > 0 && unicode.In(word[len(word)-1], unicode.Han) {
// push 字 into results & clear word
results = append(results, string(word))
word = []rune{}
word = append(word, r)
continue
}
word = append(word, r)
}
if len(word) > 0 {
results = append(results, string(word))
}
return results
}
func (ctx *Context) textWrap(s string, maxWidth float64) []string {
parts := breakWords(s)
lines := []string{}
line := ""
for _, u := range parts {
// will not appear
if u == "\n" {
lines = append(lines, line)
lines = append(lines, "")
line = ""
continue
}
if w, _ := ctx.MeasureString(line + u); w >= maxWidth {
lines = append(lines, line)
line = u
continue
}
line += u
}
if len(line) > 0 {
lines = append(lines, line)
}
return lines
}