gg/wrap.go

59 lines
1.0 KiB
Go
Raw Permalink Normal View History

2016-02-24 23:22:21 +01:00
package gg
import (
"strings"
"unicode"
)
type measureStringer interface {
MeasureString(s string) (w, h float64)
}
func splitOnSpace(x string) []string {
var result []string
pi := 0
ps := false
for i, c := range x {
s := unicode.IsSpace(c)
if s != ps && i > 0 {
result = append(result, x[pi:i])
pi = i
}
ps = s
}
result = append(result, x[pi:])
return result
}
func wordWrap(m measureStringer, s string, width float64) []string {
var result []string
for _, line := range strings.Split(s, "\n") {
fields := splitOnSpace(line)
2016-02-25 03:26:51 +01:00
if len(fields)%2 == 1 {
fields = append(fields, "")
2016-02-24 23:22:21 +01:00
}
2016-02-25 03:26:51 +01:00
x := ""
2016-02-24 23:22:21 +01:00
for i := 0; i < len(fields); i += 2 {
2016-02-25 03:26:51 +01:00
w, _ := m.MeasureString(x + fields[i])
if w > width {
if x == "" {
result = append(result, fields[i])
x = ""
2016-02-24 23:22:21 +01:00
continue
} else {
2016-02-25 03:26:51 +01:00
result = append(result, x)
x = ""
2016-02-24 23:22:21 +01:00
}
}
2016-02-25 03:26:51 +01:00
x += fields[i] + fields[i+1]
2016-02-24 23:22:21 +01:00
}
2016-02-25 03:26:51 +01:00
if x != "" {
result = append(result, x)
2016-02-24 23:22:21 +01:00
}
}
for i, line := range result {
result[i] = strings.TrimSpace(line)
}
return result
}