WrapLayoutGroup.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections.Generic;
  4. [AddComponentMenu("Layout/Wrap Layout Group")]
  5. public class WrapLayoutGroup : LayoutGroup
  6. {
  7. public float spacingX = 10;
  8. public float spacingY = 10;
  9. public override void CalculateLayoutInputHorizontal()
  10. {
  11. base.CalculateLayoutInputHorizontal();
  12. CalcAlongAxis(0);
  13. }
  14. public override void CalculateLayoutInputVertical()
  15. {
  16. CalcAlongAxis(1);
  17. }
  18. public override void SetLayoutHorizontal()
  19. {
  20. SetChildrenLayout(0);
  21. }
  22. public override void SetLayoutVertical()
  23. {
  24. SetChildrenLayout(1);
  25. }
  26. void CalcAlongAxis(int axis)
  27. {
  28. float width = rectTransform.rect.width;
  29. float curX = padding.left;
  30. float curY = padding.top;
  31. float maxHeightInRow = 0;
  32. for (int i = 0; i < rectChildren.Count; i++)
  33. {
  34. RectTransform child = rectChildren[i];
  35. float childWidth = LayoutUtility.GetPreferredSize(child, 0);
  36. float childHeight = LayoutUtility.GetPreferredSize(child, 1);
  37. if (curX + childWidth + padding.right > width)
  38. {
  39. curX = padding.left;
  40. curY += maxHeightInRow + spacingY;
  41. maxHeightInRow = 0;
  42. }
  43. curX += childWidth + spacingX;
  44. maxHeightInRow = Mathf.Max(maxHeightInRow, childHeight);
  45. }
  46. float totalHeight = curY + maxHeightInRow + padding.bottom;
  47. SetLayoutInputForAxis(totalHeight, totalHeight, -1, axis);
  48. }
  49. void SetChildrenLayout(int axis)
  50. {
  51. float width = rectTransform.rect.width;
  52. float curX = padding.left;
  53. float curY = padding.top;
  54. float maxHeightInRow = 0;
  55. for (int i = 0; i < rectChildren.Count; i++)
  56. {
  57. RectTransform child = rectChildren[i];
  58. float childWidth = LayoutUtility.GetPreferredSize(child, 0);
  59. float childHeight = LayoutUtility.GetPreferredSize(child, 1);
  60. if (curX + childWidth + padding.right > width)
  61. {
  62. curX = padding.left;
  63. curY += maxHeightInRow + spacingY;
  64. maxHeightInRow = 0;
  65. }
  66. SetChildAlongAxis(child, 0, curX, childWidth);
  67. SetChildAlongAxis(child, 1, curY, childHeight);
  68. curX += childWidth + spacingX;
  69. maxHeightInRow = Mathf.Max(maxHeightInRow, childHeight);
  70. }
  71. }
  72. }