text.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package cache
  2. import (
  3. "sync"
  4. "fyne.io/fyne/v2"
  5. )
  6. var (
  7. fontSizeCache = map[fontSizeEntry]fontMetric{}
  8. fontSizeLock = sync.RWMutex{}
  9. )
  10. type fontMetric struct {
  11. size fyne.Size
  12. baseLine float32
  13. }
  14. type fontSizeEntry struct {
  15. text string
  16. size float32
  17. style fyne.TextStyle
  18. }
  19. // GetFontMetrics looks up a calculated size and baseline required for the specified text parameters.
  20. func GetFontMetrics(text string, fontSize float32, style fyne.TextStyle) (size fyne.Size, base float32) {
  21. ent := fontSizeEntry{text, fontSize, style}
  22. fontSizeLock.RLock()
  23. ret, ok := fontSizeCache[ent]
  24. fontSizeLock.RUnlock()
  25. if !ok {
  26. return fyne.Size{Width: 0, Height: 0}, 0
  27. }
  28. return ret.size, ret.baseLine
  29. }
  30. // SetFontMetrics stores a calculated font size and baseline for parameters that were missing from the cache.
  31. func SetFontMetrics(text string, fontSize float32, style fyne.TextStyle, size fyne.Size, base float32) {
  32. ent := fontSizeEntry{text, fontSize, style}
  33. fontSizeLock.Lock()
  34. fontSizeCache[ent] = fontMetric{size: size, baseLine: base}
  35. fontSizeLock.Unlock()
  36. }