gg/wrap.go

38 lines
659 B
Go
Raw Normal View History

2016-02-24 23:22:21 +01:00
package gg
import (
"strings"
)
type measureStringer interface {
MeasureString(s string) (w, h float64)
}
func wordWrap(m measureStringer, s string, width float64) []string {
var result []string
for _, line := range strings.Split(s, "\n") {
2016-02-25 03:26:51 +01:00
x := ""
2021-02-22 11:14:23 +01:00
for _, c := range line {
w, _ := m.MeasureString(x + string(c))
2016-02-25 03:26:51 +01:00
if w > width {
if x == "" {
2021-02-22 11:14:23 +01:00
result = append(result, string(c))
2016-02-25 03:26:51 +01:00
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
}
}
2021-02-22 11:14:23 +01:00
x += string(c)
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
}