From 7a6b8e102104fab8a446bb4313f98371638b2584 Mon Sep 17 00:00:00 2001 From: Jiang-Red <1343396474@qq.com> Date: Wed, 11 Jan 2023 22:06:04 +0800 Subject: [PATCH] zbputils -> rendercard --- utils.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/utils.go b/utils.go index 29db211..4efb0ff 100644 --- a/utils.go +++ b/utils.go @@ -3,6 +3,7 @@ package rendercard import ( "image" "image/color" + "strings" "github.com/Coloured-glaze/gg" ) @@ -40,3 +41,41 @@ func Transparency(dst image.Image, magnification float64) image.Image { } return dstr } + +// Truncate 截断文字 +func Truncate(fontfile string, texts []string, maxW, fontsize float64) ([]string, error) { + one := gg.NewContext(1, 1) + err := one.LoadFontFace(fontfile, fontsize) + if err != nil { + return nil, err + } + newtexts := make([]string, 0, len(texts)*2) + for i := 0; i < len(texts); i++ { + newlinetext, textw, tmpw := "", 0.0, 0.0 + text := texts[i] + for len(texts[i]) > 0 { + var tmp strings.Builder + tmp.Grow(len(text)) + res := make([]rune, 0, len(text)) + for _, r := range text { + tmp.WriteRune(r) + width, _ := one.MeasureString(tmp.String()) // 获取文字宽度 + if width > maxW { // 如果宽度大于文字边距 + break // 跳出 + } else { + res = append(res, r) // 写入 + } + newlinetext = string(res) + } + newtexts = append(newtexts, newlinetext) + if tmpw > textw { + textw = tmpw + } + if len(newlinetext) >= len(texts[i]) { + break + } + texts[i] = texts[i][len(newlinetext):] + } + } + return newtexts, nil +}