From 00f4b03eccf9c1b462f43c97f419565e5994cb34 Mon Sep 17 00:00:00 2001 From: m-hosoi Date: Mon, 22 Feb 2021 19:14:23 +0900 Subject: [PATCH] fix: wrap multibyte char --- wrap.go | 29 ++++------------------------- 1 file changed, 4 insertions(+), 25 deletions(-) diff --git a/wrap.go b/wrap.go index 3dfe6e1..4d4f01b 100644 --- a/wrap.go +++ b/wrap.go @@ -2,42 +2,21 @@ 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) - if len(fields)%2 == 1 { - fields = append(fields, "") - } x := "" - for i := 0; i < len(fields); i += 2 { - w, _ := m.MeasureString(x + fields[i]) + for _, c := range line { + w, _ := m.MeasureString(x + string(c)) if w > width { if x == "" { - result = append(result, fields[i]) + result = append(result, string(c)) x = "" continue } else { @@ -45,7 +24,7 @@ func wordWrap(m measureStringer, s string, width float64) []string { x = "" } } - x += fields[i] + fields[i+1] + x += string(c) } if x != "" { result = append(result, x)