gridwraplayout.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. padding := theme.Padding()
  23. g.colCount = 1
  24. g.rowCount = 0
  25. if size.Width > g.CellSize.Width {
  26. g.colCount = int(math.Floor(float64(size.Width+padding) / float64(g.CellSize.Width+padding)))
  27. }
  28. i, x, y := 0, float32(0), float32(0)
  29. for _, child := range objects {
  30. if !child.Visible() {
  31. continue
  32. }
  33. if i%g.colCount == 0 {
  34. g.rowCount++
  35. }
  36. child.Move(fyne.NewPos(x, y))
  37. child.Resize(g.CellSize)
  38. if (i+1)%g.colCount == 0 {
  39. x = 0
  40. y += g.CellSize.Height + padding
  41. } else {
  42. x += g.CellSize.Width + padding
  43. }
  44. i++
  45. }
  46. }
  47. // MinSize finds the smallest size that satisfies all the child objects.
  48. // For a GridWrapLayout this is simply the specified cellsize as a single column
  49. // layout has no padding. The returned size does not take into account the number
  50. // of columns as this layout re-flows dynamically.
  51. func (g *gridWrapLayout) MinSize(objects []fyne.CanvasObject) fyne.Size {
  52. rows := g.rowCount
  53. if rows < 1 {
  54. rows = 1
  55. }
  56. return fyne.NewSize(g.CellSize.Width,
  57. (g.CellSize.Height*float32(rows))+(float32(rows-1)*theme.Padding()))
  58. }