1
0
Fork 0
mirror of https://github.com/Luzifer/badge-gen.git synced 2024-11-08 13:20:02 +00:00
badge-gen/font.go
Knut Ahlers 73b722d998
Replace bindata with go:embed
Signed-off-by: Knut Ahlers <knut@ahlers.me>
2023-09-07 18:12:11 +02:00

39 lines
998 B
Go

// Some of this code (namely the code for computing the
// width of a string in a given font) was copied from
// code.google.com/p/freetype-go/freetype/ which includes
// the following copyright notice:
// Copyright 2010 The Freetype-Go Authors. All rights reserved.
package main
import (
"github.com/golang/freetype/truetype"
"golang.org/x/image/math/fixed"
)
const (
fontSize = 11
)
func calculateTextWidth(text string) (int, error) {
binFont, _ := assets.ReadFile("assets/DejaVuSans.ttf")
font, err := truetype.Parse(binFont)
if err != nil {
return 0, err
}
scale := fontSize / float64(font.FUnitsPerEm())
width := 0
prev, hasPrev := truetype.Index(0), false
for _, rune := range text {
fUnitsPerEm := fixed.Int26_6(font.FUnitsPerEm())
index := font.Index(rune)
if hasPrev {
width += int(font.Kern(fUnitsPerEm, prev, index))
}
width += int(font.HMetric(fUnitsPerEm, index).AdvanceWidth)
prev, hasPrev = index, true
}
return int(float64(width) * scale), nil
}