FlowLayout.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #include "Base.h"
  2. #include "Control.h"
  3. #include "FlowLayout.h"
  4. #include "Container.h"
  5. namespace gameplay
  6. {
  7. static FlowLayout* __instance;
  8. FlowLayout::FlowLayout() : _horizontalSpacing(0), _verticalSpacing(0)
  9. {
  10. }
  11. FlowLayout::~FlowLayout()
  12. {
  13. __instance = NULL;
  14. }
  15. FlowLayout* FlowLayout::create()
  16. {
  17. if (!__instance)
  18. {
  19. __instance = new FlowLayout();
  20. }
  21. else
  22. {
  23. __instance->addRef();
  24. }
  25. return __instance;
  26. }
  27. Layout::Type FlowLayout::getType()
  28. {
  29. return Layout::LAYOUT_FLOW;
  30. }
  31. int FlowLayout::getHorizontalSpacing() const
  32. {
  33. return _horizontalSpacing;
  34. }
  35. int FlowLayout::getVerticalSpacing() const
  36. {
  37. return _verticalSpacing;
  38. }
  39. void FlowLayout::setSpacing(int horizontalSpacing, int verticalSpacing)
  40. {
  41. _horizontalSpacing = horizontalSpacing;
  42. _verticalSpacing = verticalSpacing;
  43. }
  44. void FlowLayout::update(const Container* container)
  45. {
  46. GP_ASSERT(container);
  47. const Rectangle& containerBounds = container->getBounds();
  48. const Theme::Border& containerBorder = container->getBorder(container->getState());
  49. const Theme::Padding& containerPadding = container->getPadding();
  50. float clipWidth = containerBounds.width - containerBorder.left - containerBorder.right - containerPadding.left - containerPadding.right;
  51. float clipHeight = containerBounds.height - containerBorder.top - containerBorder.bottom - containerPadding.top - containerPadding.bottom;
  52. float xPosition = 0;
  53. float yPosition = 0;
  54. float rowY = 0;
  55. float tallestHeight = 0;
  56. std::vector<Control*> controls = container->getControls();
  57. for (size_t i = 0, controlsCount = controls.size(); i < controlsCount; i++)
  58. {
  59. Control* control = controls.at(i);
  60. GP_ASSERT(control);
  61. if (!control->isVisible())
  62. continue;
  63. const Rectangle& bounds = control->getBounds();
  64. const Theme::Margin& margin = control->getMargin();
  65. xPosition += margin.left;
  66. // Wrap to next row if we've gone past the edge of the container.
  67. if (xPosition + bounds.width >= clipWidth)
  68. {
  69. xPosition = margin.left;
  70. rowY += tallestHeight + _verticalSpacing;
  71. tallestHeight = 0;
  72. }
  73. yPosition = rowY + margin.top;
  74. control->setPosition(xPosition, yPosition);
  75. xPosition += bounds.width + margin.right + _horizontalSpacing;
  76. float height = bounds.height + margin.top + margin.bottom;
  77. if (height > tallestHeight)
  78. {
  79. tallestHeight = height;
  80. }
  81. }
  82. }
  83. }