Files
beatglow/draw/font/font.go
T
2026-10-29 17:29:41 +01:00

88 lines
1.9 KiB
Go

package font
import (
"image"
"image/color"
"image/draw"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
// Font is a bitmap font.
type Font struct {
GlyphWith int
GlyphHeight int
Spacing int
glyphs map[rune][]uint16
glyphsV bool
}
func (f *Font) render(out draw.Image, c color.Color, x, y int, pixels []uint16) int {
if f.glyphsV {
for i, bits := range pixels {
for j := 0; j < f.GlyphWith; j++ {
if bits&(1<<j) != 0 {
out.Set(x+(f.GlyphWith-j-1), y+i, c)
}
}
}
} else {
for dx := 0; dx < f.GlyphWith; dx++ {
for dy := 0; dy < f.GlyphHeight; dy++ {
if pixels[dx]&(1<<dy) != 0 {
out.Set(x+dx, y+dy, c)
}
}
}
}
return f.GlyphWith + f.Spacing
}
func (r *Font) Measure(text string) image.Point {
switch size := len(text); size {
case 0:
return image.Point{}
case 1:
return image.Point{X: r.GlyphWith, Y: r.GlyphHeight}
default:
return image.Point{X: r.GlyphWith*size + r.Spacing*size - r.Spacing, Y: r.GlyphHeight}
}
}
func (f *Font) PrintChar(dst draw.Image, c color.Color, x, y int, r rune) int {
if b := dst.Bounds(); !image.Pt(x, y).In(b) {
// Fast path for out of bounds.
return f.GlyphWith + f.Spacing
}
if r == ' ' {
// Fast path for spaces.
return f.GlyphWith + f.Spacing
}
if pixels, ok := f.glyphs[r]; ok {
return f.render(dst, c, x, y, pixels)
} else if r == '?' {
// Glyph was a question mark, but we don't have it, treat it as a space.
return f.PrintChar(dst, c, x, y, ' ')
}
return f.PrintChar(dst, c, x, y, normalizeRune(r))
}
func (f *Font) Print(dst draw.Image, c color.Color, x, y int, text string) {
for _, r := range []rune(text) {
x += f.PrintChar(dst, c, x, y, r)
}
}
func normalizeRune(r rune) rune {
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
result, _, err := transform.String(t, string(r))
if err != nil {
return '?'
}
return []rune(result)[0]
}