fix: wrap multibyte char

This commit is contained in:
m-hosoi 2021-02-22 19:14:23 +09:00
parent af4cd58078
commit 00f4b03ecc

29
wrap.go
View File

@ -2,42 +2,21 @@ package gg
import ( import (
"strings" "strings"
"unicode"
) )
type measureStringer interface { type measureStringer interface {
MeasureString(s string) (w, h float64) 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 { func wordWrap(m measureStringer, s string, width float64) []string {
var result []string var result []string
for _, line := range strings.Split(s, "\n") { for _, line := range strings.Split(s, "\n") {
fields := splitOnSpace(line)
if len(fields)%2 == 1 {
fields = append(fields, "")
}
x := "" x := ""
for i := 0; i < len(fields); i += 2 { for _, c := range line {
w, _ := m.MeasureString(x + fields[i]) w, _ := m.MeasureString(x + string(c))
if w > width { if w > width {
if x == "" { if x == "" {
result = append(result, fields[i]) result = append(result, string(c))
x = "" x = ""
continue continue
} else { } else {
@ -45,7 +24,7 @@ func wordWrap(m measureStringer, s string, width float64) []string {
x = "" x = ""
} }
} }
x += fields[i] + fields[i+1] x += string(c)
} }
if x != "" { if x != "" {
result = append(result, x) result = append(result, x)