text.go 991 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // SPDX-License-Identifier: Unlicense OR MIT
  2. package text
  3. import (
  4. "fmt"
  5. "gioui.org/io/system"
  6. "golang.org/x/image/math/fixed"
  7. )
  8. type Alignment uint8
  9. const (
  10. Start Alignment = iota
  11. End
  12. Middle
  13. )
  14. func (a Alignment) String() string {
  15. switch a {
  16. case Start:
  17. return "Start"
  18. case End:
  19. return "End"
  20. case Middle:
  21. return "Middle"
  22. default:
  23. panic("invalid Alignment")
  24. }
  25. }
  26. // Align returns the x offset that should be applied to text with width so that it
  27. // appears correctly aligned within a space of size maxWidth and with the primary
  28. // text direction dir.
  29. func (a Alignment) Align(dir system.TextDirection, width fixed.Int26_6, maxWidth int) fixed.Int26_6 {
  30. mw := fixed.I(maxWidth)
  31. if dir.Progression() == system.TowardOrigin {
  32. switch a {
  33. case Start:
  34. a = End
  35. case End:
  36. a = Start
  37. }
  38. }
  39. switch a {
  40. case Middle:
  41. return (mw - width) / 2
  42. case End:
  43. return (mw - width)
  44. case Start:
  45. return 0
  46. default:
  47. panic(fmt.Errorf("unknown alignment %v", a))
  48. }
  49. }