Skip to content

Commit

Permalink
zbputils -> rendercard
Browse files Browse the repository at this point in the history
  • Loading branch information
Jiang-Red committed Jan 11, 2023
1 parent 5f8d9a2 commit 7a6b8e1
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package rendercard
import (
"image"
"image/color"
"strings"

"github.com/Coloured-glaze/gg"
)
Expand Down Expand Up @@ -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
}

0 comments on commit 7a6b8e1

Please sign in to comment.