78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
//nolint:mnd
|
|
package fbdraw
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.eeqj.de/sneak/hdmistat/internal/font"
|
|
"github.com/golang/freetype"
|
|
"github.com/golang/freetype/truetype"
|
|
"golang.org/x/image/font/gofont/goregular"
|
|
)
|
|
|
|
// CalculateCharDimensions calculates the character dimensions for a given font and size
|
|
func CalculateCharDimensions(
|
|
fontFamily font.FontFamily,
|
|
fontSize float64,
|
|
) (charWidth, charHeight int, err error) {
|
|
// Load a sample font to measure
|
|
f, err := font.LoadFont(fontFamily, font.WeightRegular, false)
|
|
if err != nil {
|
|
// Fallback to built-in font
|
|
f, err = truetype.Parse(goregular.TTF)
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
}
|
|
|
|
// Create a context to measure font metrics
|
|
c := freetype.NewContext()
|
|
c.SetFont(f)
|
|
c.SetFontSize(fontSize)
|
|
c.SetDPI(72)
|
|
|
|
// Get font face for measurements
|
|
face := truetype.NewFace(f, &truetype.Options{
|
|
Size: fontSize,
|
|
DPI: 72,
|
|
})
|
|
|
|
// For monospace fonts, get the advance width
|
|
advance, _ := face.GlyphAdvance('M')
|
|
charWidth = advance.Round() - 1 // Slightly tighter kerning
|
|
|
|
// Get line height from metrics
|
|
metrics := face.Metrics()
|
|
charHeight = metrics.Height.Round() + 3 // Add extra leading for better line spacing
|
|
|
|
fmt.Printf(
|
|
"Font metrics: advance=%v (rounded=%d), height=%v (rounded=%d, with +3 leading)\n",
|
|
advance,
|
|
charWidth,
|
|
metrics.Height,
|
|
charHeight,
|
|
)
|
|
|
|
return charWidth, charHeight, nil
|
|
}
|
|
|
|
// CalculateGridSize calculates the grid dimensions that fit in the given pixel dimensions
|
|
func CalculateGridSize(
|
|
pixelWidth, pixelHeight int,
|
|
fontFamily font.FontFamily,
|
|
fontSize float64,
|
|
) (gridWidth, gridHeight int, err error) {
|
|
charWidth, charHeight, err := CalculateCharDimensions(
|
|
fontFamily,
|
|
fontSize,
|
|
)
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
|
|
gridWidth = pixelWidth / charWidth
|
|
gridHeight = pixelHeight / charHeight
|
|
|
|
return gridWidth, gridHeight, nil
|
|
}
|