gridwraplayout.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package layout
  2. import (
  3. "math"
  4. "fyne.io/fyne/v2"
  5. "fyne.io/fyne/v2/theme"
  6. )
  7. // Declare conformity with Layout interface
  8. var _ fyne.Layout = (*gridWrapLayout)(nil)
  9. type gridWrapLayout struct {
  10. CellSize fyne.Size
  11. colCount int
  12. rowCount int
  13. }
  14. // NewGridWrapLayout returns a new GridWrapLayout instance
  15. func NewGridWrapLayout(size fyne.Size) fyne.Layout {
  16. return &gridWrapLayout{size, 1, 1}
  17. }
  18. // Layout is called to pack all child objects into a specified size.
  19. // For a GridWrapLayout this will attempt to lay all the child objects in a row
  20. // and wrap to a new row if the size is not large enough.
  21. func (g *gridWrapLayout) Layout(objects []fyne.CanvasObject, size fyne.Size) {
  22. g.colCount = 1
  23. g.rowCount = 0
  24. if size.Width > g.CellSize.Width {
  25. g.colCount = int(math.Floor(float64(size.Width+theme.Padding()) / float64(g.CellSize.Width+theme.Padding())))
  26. }
  27. i, x, y := 0, float32(0), float32(0)
  28. for _, child := range objects {
  29. if !child.Visible() {
  30. continue
  31. }
  32. if i%g.colCount == 0 {
  33. g.rowCount++
  34. }
  35. child.Move(fyne.NewPos(x, y))
  36. child.Resize(g.CellSize)
  37. if (i+1)%g.colCount == 0 {
  38. x = 0
  39. y += g.CellSize.Height + theme.Padding()
  40. } else {
  41. x += g.CellSize.Width + theme.Padding()
  42. }
  43. i++
  44. }
  45. }
  46. // MinSize finds the smallest size that satisfies all the child objects.
  47. // For a GridWrapLayout this is simply the specified cellsize as a single column
  48. // layout has no padding. The returned size does not take into account the number
  49. // of columns as this layout re-flows dynamically.
  50. func (g *gridWrapLayout) MinSize(objects []fyne.CanvasObject) fyne.Size {
  51. rows := g.rowCount
  52. if rows < 1 {
  53. rows = 1
  54. }
  55. return fyne.NewSize(g.CellSize.Width,
  56. (g.CellSize.Height*float32(rows))+(float32(rows-1)*theme.Padding()))
  57. }