using System.Collections; using System.Collections.Generic; using UnityEngine.EventSystems; using UnityEngine.Pool;
namespaceUnityEngine.UI { [DisallowMultipleComponent] [ExecuteAlways] [RequireComponent(typeof(RectTransform))] ///<summary> /// Abstract base class to use for layout groups. ///</summary> publicabstractclassLayoutGroup : UIBehaviour, ILayoutElement, ILayoutGroup { [SerializeField] protected RectOffset m_Padding = new RectOffset();
///<summary> /// The padding to add around the child layout elements. ///</summary> public RectOffset padding { get { return m_Padding; } set { SetProperty(ref m_Padding, value); } }
///<summary> /// The alignment to use for the child layout elements in the layout group. ///</summary> ///<remarks> /// If a layout element does not specify a flexible width or height, its child elements many not use the available space within the layout group. In this case, use the alignment settings to specify how to align child elements within their layout group. ///</remarks> public TextAnchor childAlignment { get { return m_ChildAlignment; } set { SetProperty(ref m_ChildAlignment, value); } }
[System.NonSerialized] private List<RectTransform> m_RectChildren = new List<RectTransform>(); protected List<RectTransform> rectChildren { get { return m_RectChildren; } }
publicvirtualvoidCalculateLayoutInputHorizontal() { m_RectChildren.Clear(); var toIgnoreList = ListPool<Component>.Get(); for (int i = 0; i < rectTransform.childCount; i++) { var rect = rectTransform.GetChild(i) as RectTransform; if (rect == null || !rect.gameObject.activeInHierarchy) continue;
///<summary> /// Callback for when properties have been changed by animation. ///</summary> protectedoverridevoidOnDidApplyAnimationProperties() { SetDirty(); }
///<summary> /// The min size for the layout group on the given axis. ///</summary> ///<param name="axis">The axis index. 0 is horizontal and 1 is vertical.</param> ///<returns>The min size</returns> protectedfloatGetTotalMinSize(int axis) { return m_TotalMinSize[axis]; }
///<summary> /// The preferred size for the layout group on the given axis. ///</summary> ///<param name="axis">The axis index. 0 is horizontal and 1 is vertical.</param> ///<returns>The preferred size.</returns> protectedfloatGetTotalPreferredSize(int axis) { return m_TotalPreferredSize[axis]; }
///<summary> /// The flexible size for the layout group on the given axis. ///</summary> ///<param name="axis">The axis index. 0 is horizontal and 1 is vertical.</param> ///<returns>The flexible size</returns> protectedfloatGetTotalFlexibleSize(int axis) { return m_TotalFlexibleSize[axis]; }
///<summary> /// Returns the calculated position of the first child layout element along the given axis. ///</summary> ///<param name="axis">The axis index. 0 is horizontal and 1 is vertical.</param> ///<param name="requiredSpaceWithoutPadding">The total space required on the given axis for all the layout elements including spacing and excluding padding.</param> ///<returns>The position of the first child along the given axis.</returns> protectedfloatGetStartOffset(int axis, float requiredSpaceWithoutPadding) { float requiredSpace = requiredSpaceWithoutPadding + (axis == 0 ? padding.horizontal : padding.vertical); float availableSpace = rectTransform.rect.size[axis]; float surplusSpace = availableSpace - requiredSpace; float alignmentOnAxis = GetAlignmentOnAxis(axis); return (axis == 0 ? padding.left : padding.top) + surplusSpace * alignmentOnAxis; }
///<summary> /// Returns the alignment on the specified axis as a fraction where 0 is left/top, 0.5 is middle, and 1 is right/bottom. ///</summary> ///<param name="axis">The axis to get alignment along. 0 is horizontal and 1 is vertical.</param> ///<returns>The alignment as a fraction where 0 is left/top, 0.5 is middle, and 1 is right/bottom.</returns> protectedfloatGetAlignmentOnAxis(int axis) { if (axis == 0) return ((int)childAlignment % 3) * 0.5f; else return ((int)childAlignment / 3) * 0.5f; }
///<summary> /// Used to set the calculated layout properties for the given axis. ///</summary> ///<param name="totalMin">The min size for the layout group.</param> ///<param name="totalPreferred">The preferred size for the layout group.</param> ///<param name="totalFlexible">The flexible size for the layout group.</param> ///<param name="axis">The axis to set sizes for. 0 is horizontal and 1 is vertical.</param> protectedvoidSetLayoutInputForAxis(float totalMin, float totalPreferred, float totalFlexible, int axis) { m_TotalMinSize[axis] = totalMin; m_TotalPreferredSize[axis] = totalPreferred; m_TotalFlexibleSize[axis] = totalFlexible; }
///<summary> /// Set the position and size of a child layout element along the given axis. ///</summary> ///<param name="rect">The RectTransform of the child layout element.</param> ///<param name="axis">The axis to set the position and size along. 0 is horizontal and 1 is vertical.</param> ///<param name="pos">The position from the left side or top.</param> protectedvoidSetChildAlongAxis(RectTransform rect, int axis, float pos) { if (rect == null) return;
///<summary> /// Set the position and size of a child layout element along the given axis. ///</summary> ///<param name="rect">The RectTransform of the child layout element.</param> ///<param name="axis">The axis to set the position and size along. 0 is horizontal and 1 is vertical.</param> ///<param name="pos">The position from the left side or top.</param> protectedvoidSetChildAlongAxisWithScale(RectTransform rect, int axis, float pos, float scaleFactor) { if (rect == null) return;
// Inlined rect.SetInsetAndSizeFromParentEdge(...) and refactored code in order to multiply desired size by scaleFactor. // sizeDelta must stay the same but the size used in the calculation of the position must be scaled by the scaleFactor.
///<summary> /// Set the position and size of a child layout element along the given axis. ///</summary> ///<param name="rect">The RectTransform of the child layout element.</param> ///<param name="axis">The axis to set the position and size along. 0 is horizontal and 1 is vertical.</param> ///<param name="pos">The position from the left side or top.</param> ///<param name="size">The size.</param> protectedvoidSetChildAlongAxis(RectTransform rect, int axis, float pos, float size) { if (rect == null) return;
///<summary> /// Set the position and size of a child layout element along the given axis. ///</summary> ///<param name="rect">The RectTransform of the child layout element.</param> ///<param name="axis">The axis to set the position and size along. 0 is horizontal and 1 is vertical.</param> ///<param name="pos">The position from the left side or top.</param> ///<param name="size">The size.</param> protectedvoidSetChildAlongAxisWithScale(RectTransform rect, int axis, float pos, float size, float scaleFactor) { if (rect == null) return;
// Inlined rect.SetInsetAndSizeFromParentEdge(...) and refactored code in order to multiply desired size by scaleFactor. // sizeDelta must stay the same but the size used in the calculation of the position must be scaled by the scaleFactor.
///<summary> /// Helper method used to set a given property if it has changed. ///</summary> ///<param name="currentValue">A reference to the member value.</param> ///<param name="newValue">The new value.</param> protectedvoidSetProperty<T>(ref T currentValue, T newValue) { if ((currentValue == null && newValue == null) || (currentValue != null && currentValue.Equals(newValue))) return; currentValue = newValue; SetDirty(); }
///<summary> /// Mark the LayoutGroup as dirty. ///</summary> protectedvoidSetDirty() { if (!IsActive()) return;
if (!CanvasUpdateRegistry.IsRebuildingLayout()) LayoutRebuilder.MarkLayoutForRebuild(rectTransform); else StartCoroutine(DelayedSetDirty(rectTransform)); }
publicvirtualvoidCalculateLayoutInputHorizontal() { m_RectChildren.Clear(); var toIgnoreList = ListPool<Component>.Get(); for (int i = 0; i < rectTransform.childCount; i++) { var rect = rectTransform.GetChild(i) as RectTransform; if (rect == null || !rect.gameObject.activeInHierarchy) continue;
///<summary> /// Set the position and size of a child layout element along the given axis. ///</summary> ///<param name="rect">The RectTransform of the child layout element.</param> ///<param name="axis">The axis to set the position and size along. 0 is horizontal and 1 is vertical.</param> ///<param name="pos">The position from the left side or top.</param> ///<param name="size">The size.</param> protectedvoidSetChildAlongAxisWithScale(RectTransform rect, int axis, float pos, float size, float scaleFactor) { if (rect == null) return;
// Inlined rect.SetInsetAndSizeFromParentEdge(...) and refactored code in order to multiply desired size by scaleFactor. // sizeDelta must stay the same but the size used in the calculation of the position must be scaled by the scaleFactor.
namespaceUnityEngine.UI { ///<summary> /// Utility functions for querying layout elements for their minimum, preferred, and flexible sizes. ///</summary> publicstaticclassLayoutUtility { ///<summary> /// Returns the minimum size of the layout element. ///</summary> ///<param name="rect">The RectTransform of the layout element to query.</param> ///<param name="axis">The axis to query. This can be 0 or 1.</param> ///<remarks>All components on the GameObject that implement the ILayoutElement are queried. The one with the highest priority which has a value for this setting is used. If multiple componets have this setting and have the same priority, the maximum value out of those is used.</remarks> publicstaticfloatGetMinSize(RectTransform rect, int axis) { return axis == 0 ? GetMinWidth(rect) : GetMinHeight(rect); }
///<summary> /// Returns the preferred size of the layout element. ///</summary> ///<param name="rect">The RectTransform of the layout element to query.</param> ///<param name="axis">The axis to query. This can be 0 or 1.</param> ///<remarks> /// All components on the GameObject that implement the ILayoutElement are queried. The one with the highest priority which has a value for this setting is used. If multiple componets have this setting and have the same priority, the maximum value out of those is used. ///</remarks> publicstaticfloatGetPreferredSize(RectTransform rect, int axis) { return axis == 0 ? GetPreferredWidth(rect) : GetPreferredHeight(rect); }
///<summary> /// Returns the flexible size of the layout element. ///</summary> ///<remarks> /// All components on the GameObject that implement the ILayoutElement are queried. The one with the highest priority which has a value for this setting is used. If multiple componets have this setting and have the same priority, the maximum value out of those is used. ///</remarks> ///<param name="rect">The RectTransform of the layout element to query.</param> ///<param name="axis">The axis to query. This can be 0 or 1.</param> publicstaticfloatGetFlexibleSize(RectTransform rect, int axis) { return axis == 0 ? GetFlexibleWidth(rect) : GetFlexibleHeight(rect); }
///<summary> /// Returns the minimum width of the layout element. ///</summary> ///<param name="rect">The RectTransform of the layout element to query.</param> ///<remarks> /// All components on the GameObject that implement the ILayoutElement are queried. The one with the highest priority which has a value for this setting is used. If multiple componets have this setting and have the same priority, the maximum value out of those is used. ///</remarks> publicstaticfloatGetMinWidth(RectTransform rect) { return GetLayoutProperty(rect, e => e.minWidth, 0); }
///<summary> /// Returns the preferred width of the layout element. ///</summary> ///<param name="rect">The RectTransform of the layout element to query.</param> ///<returns> /// All components on the GameObject that implement the ILayoutElement are queried. The one with the highest priority which has a value for this setting is used. If multiple componets have this setting and have the same priority, the maximum value out of those is used. ///</returns> publicstaticfloatGetPreferredWidth(RectTransform rect) { return Mathf.Max(GetLayoutProperty(rect, e => e.minWidth, 0), GetLayoutProperty(rect, e => e.preferredWidth, 0)); }
///<summary> /// Returns the flexible width of the layout element. ///</summary> ///<remarks> /// All components on the GameObject that implement the ILayoutElement are queried. The one with the highest priority which has a value for this setting is used. If multiple componets have this setting and have the same priority, the maximum value out of those is used ///</remarks> ///<param name="rect">The RectTransform of the layout element to query.</param> publicstaticfloatGetFlexibleWidth(RectTransform rect) { return GetLayoutProperty(rect, e => e.flexibleWidth, 0); }
///<summary> /// Returns the minimum height of the layout element. ///</summary> ///<param name="rect">The RectTransform of the layout element to query.</param> ///<remarks> /// All components on the GameObject that implement the ILayoutElement are queried. The one with the highest priority which has a value for this setting is used. If multiple componets have this setting and have the same priority, the maximum value out of those is used. ///</remarks> publicstaticfloatGetMinHeight(RectTransform rect) { return GetLayoutProperty(rect, e => e.minHeight, 0); }
///<summary> /// Returns the preferred height of the layout element. ///</summary> ///<param name="rect">The RectTransform of the layout element to query.</param> ///<remarks> /// All components on the GameObject that implement the ILayoutElement are queried. The one with the highest priority which has a value for this setting is used. If multiple componets have this setting and have the same priority, the maximum value out of those is used. ///</remarks> publicstaticfloatGetPreferredHeight(RectTransform rect) { return Mathf.Max(GetLayoutProperty(rect, e => e.minHeight, 0), GetLayoutProperty(rect, e => e.preferredHeight, 0)); }
///<summary> /// Returns the flexible height of the layout element. ///</summary> ///<remarks> /// All components on the GameObject that implement the ILayoutElement are queried. The one with the highest priority which has a value for this setting is used. If multiple componets have this setting and have the same priority, the maximum value out of those is used. ///</remarks> ///<param name="rect">The RectTransform of the layout element to query.</param> publicstaticfloatGetFlexibleHeight(RectTransform rect) { return GetLayoutProperty(rect, e => e.flexibleHeight, 0); }
///<summary> /// Gets a calculated layout property for the layout element with the given RectTransform. ///</summary> ///<param name="rect">The RectTransform of the layout element to get a property for.</param> ///<param name="property">The property to calculate.</param> ///<param name="defaultValue">The default value to use if no component on the layout element supplies the given property</param> ///<returns>The calculated value of the layout property.</returns> publicstaticfloatGetLayoutProperty(RectTransform rect, System.Func<ILayoutElement, float> property, float defaultValue) { ILayoutElement dummy; return GetLayoutProperty(rect, property, defaultValue, out dummy); }
///<summary> /// Gets a calculated layout property for the layout element with the given RectTransform. ///</summary> ///<param name="rect">The RectTransform of the layout element to get a property for.</param> ///<param name="property">The property to calculate.</param> ///<param name="defaultValue">The default value to use if no component on the layout element supplies the given property</param> ///<param name="source">Optional out parameter to get the component that supplied the calculated value.</param> ///<returns>The calculated value of the layout property.</returns> publicstaticfloatGetLayoutProperty(RectTransform rect, System.Func<ILayoutElement, float> property, float defaultValue, out ILayoutElement source) { source = null; if (rect == null) return0; float min = defaultValue; int maxPriority = System.Int32.MinValue; var components = ListPool<Component>.Get(); rect.GetComponents(typeof(ILayoutElement), components);
var componentsCount = components.Count; for (int i = 0; i < componentsCount; i++) { var layoutComp = components[i] as ILayoutElement; if (layoutComp is Behaviour && !((Behaviour)layoutComp).isActiveAndEnabled) continue;
int priority = layoutComp.layoutPriority; // If this layout components has lower priority than a previously used, ignore it. if (priority < maxPriority) continue; float prop = property(layoutComp); // If this layout property is set to a negative value, it means it should be ignored. if (prop < 0) continue;
// If this layout component has higher priority than all previous ones, // overwrite with this one's value. if (priority > maxPriority) { min = prop; maxPriority = priority; source = layoutComp; } // If the layout component has the same priority as a previously used, // use the largest of the values with the same priority. elseif (prop > min) { min = prop; source = layoutComp; } }
publicstaticfloatGetLayoutProperty(RectTransform rect, System.Func<ILayoutElement, float> property, float defaultValue, out ILayoutElement source) { source = null; if (rect == null) return0;
float min = defaultValue; int maxPriority = System.Int32.MinValue; var components = ListPool<Component>.Get(); rect.GetComponents(typeof(ILayoutElement), components);
for (int i = 0; i < components.Count; i++) { var layoutComp = components[i] as ILayoutElement;
// 跳过未激活的 Behaviour if (layoutComp is Behaviour && !((Behaviour)layoutComp).isActiveAndEnabled) continue;
int priority = layoutComp.layoutPriority;
// 优先级低于当前最高,跳过 if (priority < maxPriority) continue;
namespaceUnityEngine.UI { ///<summary> /// Abstract base class for HorizontalLayoutGroup and VerticalLayoutGroup to generalize common functionality. ///</summary> /// [ExecuteAlways] publicabstractclassHorizontalOrVerticalLayoutGroup : LayoutGroup { [SerializeField] protectedfloat m_Spacing = 0;
///<summary> /// The spacing to use between layout elements in the layout group. ///</summary> publicfloat spacing { get { return m_Spacing; } set { SetProperty(ref m_Spacing, value); } }
///<summary> /// Whether to force the children to expand to fill additional available horizontal space. ///</summary> publicbool childForceExpandWidth { get { return m_ChildForceExpandWidth; } set { SetProperty(ref m_ChildForceExpandWidth, value); } }
///<summary> /// Whether to force the children to expand to fill additional available vertical space. ///</summary> publicbool childForceExpandHeight { get { return m_ChildForceExpandHeight; } set { SetProperty(ref m_ChildForceExpandHeight, value); } }
///<summary> /// Returns true if the Layout Group controls the widths of its children. Returns false if children control their own widths. ///</summary> ///<remarks> /// If set to false, the layout group will only affect the positions of the children while leaving the widths untouched. The widths of the children can be set via the respective RectTransforms in this case. /// /// If set to true, the widths of the children are automatically driven by the layout group according to their respective minimum, preferred, and flexible widths. This is useful if the widths of the children should change depending on how much space is available.In this case the width of each child cannot be set manually in the RectTransform, but the minimum, preferred and flexible width for each child can be controlled by adding a LayoutElement component to it. ///</remarks> publicbool childControlWidth { get { return m_ChildControlWidth; } set { SetProperty(ref m_ChildControlWidth, value); } }
///<summary> /// Returns true if the Layout Group controls the heights of its children. Returns false if children control their own heights. ///</summary> ///<remarks> /// If set to false, the layout group will only affect the positions of the children while leaving the heights untouched. The heights of the children can be set via the respective RectTransforms in this case. /// /// If set to true, the heights of the children are automatically driven by the layout group according to their respective minimum, preferred, and flexible heights. This is useful if the heights of the children should change depending on how much space is available.In this case the height of each child cannot be set manually in the RectTransform, but the minimum, preferred and flexible height for each child can be controlled by adding a LayoutElement component to it. ///</remarks> publicbool childControlHeight { get { return m_ChildControlHeight; } set { SetProperty(ref m_ChildControlHeight, value); } }
///<summary> /// Whether to use the x scale of each child when calculating its width. ///</summary> publicbool childScaleWidth { get { return m_ChildScaleWidth; } set { SetProperty(ref m_ChildScaleWidth, value); } }
///<summary> /// Whether to use the y scale of each child when calculating its height. ///</summary> publicbool childScaleHeight { get { return m_ChildScaleHeight; } set { SetProperty(ref m_ChildScaleHeight, value); } }
///<summary> /// Whether the order of children objects should be sorted in reverse. ///</summary> ///<remarks> /// If False the first child object will be positioned first. /// If True the last child object will be positioned first. ///</remarks> publicbool reverseArrangement { get { return m_ReverseArrangement; } set { SetProperty(ref m_ReverseArrangement, value); } }
///<summary> /// Set the positions and sizes of the child layout elements for the given axis. ///</summary> ///<param name="axis">The axis to handle. 0 is horizontal and 1 is vertical.</param> ///<param name="isVertical">Is this group a vertical group?</param> protectedvoidSetChildrenAlongAxis(int axis, bool isVertical) { float size = rectTransform.rect.size[axis]; bool controlSize = (axis == 0 ? m_ChildControlWidth : m_ChildControlHeight); bool useScale = (axis == 0 ? m_ChildScaleWidth : m_ChildScaleHeight); bool childForceExpandSize = (axis == 0 ? m_ChildForceExpandWidth : m_ChildForceExpandHeight); float alignmentOnAxis = GetAlignmentOnAxis(axis);
// For new added components we want these to be set to false, // so that the user's sizes won't be overwritten before they // have a chance to turn these settings off. // However, for existing components that were added before this // feature was introduced, we want it to be on be default for // backwardds compatibility. // Hence their default value is on, but we set to off in reset. m_ChildControlWidth = false; m_ChildControlHeight = false; }
privateint m_Capacity = 10; private Vector2[] m_Sizes = new Vector2[10];
protectedvirtualvoidUpdate() { if (Application.isPlaying) return;
int count = transform.childCount;
if (count > m_Capacity) { if (count > m_Capacity * 2) m_Capacity = count; else m_Capacity *= 2;
m_Sizes = new Vector2[m_Capacity]; }
// If children size change in editor, update layout (case 945680 - Child GameObjects in a Horizontal/Vertical Layout Group don't display their correct position in the Editor) bool dirty = false; for (int i = 0; i < count; i++) { RectTransform t = transform.GetChild(i) as RectTransform; if (t != null && t.sizeDelta != m_Sizes[i]) { dirty = true; m_Sizes[i] = t.sizeDelta; } }
if (dirty) LayoutRebuilder.MarkLayoutForRebuild(transform as RectTransform); }
///<summary> /// Set the positions and sizes of the child layout elements for the given axis. ///</summary> ///<param name="axis">The axis to handle. 0 is horizontal and 1 is vertical.</param> ///<param name="isVertical">Is this group a vertical group?</param> protectedvoidSetChildrenAlongAxis(int axis, bool isVertical) { float size = rectTransform.rect.size[axis]; bool controlSize = (axis == 0 ? m_ChildControlWidth : m_ChildControlHeight); bool useScale = (axis == 0 ? m_ChildScaleWidth : m_ChildScaleHeight); bool childForceExpandSize = (axis == 0 ? m_ChildForceExpandWidth : m_ChildForceExpandHeight); float alignmentOnAxis = GetAlignmentOnAxis(axis);
for (int i = startIndex; m_ReverseArrangement ? i >= endIndex : i < endIndex; i += increment) { GetChildSizes(child, axis, controlSize, childForceExpandSize, out min, out preferred, out flexible); float scaleFactor = useScale ? child.localScale[axis] : 1f;
[AddComponentMenu("Layout/Horizontal Layout Group", 150)] ///<summary> /// Layout class for arranging child elements side by side. ///</summary> publicclassHorizontalLayoutGroup : HorizontalOrVerticalLayoutGroup { protectedHorizontalLayoutGroup() {}
///<summary> /// Called by the layout system. Also see ILayoutElement ///</summary> publicoverridevoidCalculateLayoutInputHorizontal() { base.CalculateLayoutInputHorizontal(); CalcAlongAxis(0, false); }
///<summary> /// Called by the layout system. Also see ILayoutElement ///</summary> publicoverridevoidCalculateLayoutInputVertical() { CalcAlongAxis(1, false); }
///<summary> /// Called by the layout system. Also see ILayoutElement ///</summary> publicoverridevoidSetLayoutHorizontal() { SetChildrenAlongAxis(0, false); }
///<summary> /// Called by the layout system. Also see ILayoutElement ///</summary> publicoverridevoidSetLayoutVertical() { SetChildrenAlongAxis(1, false); } }
///<summary> /// Called by the layout system. Also see ILayoutElement ///</summary> publicoverridevoidCalculateLayoutInputHorizontal() { base.CalculateLayoutInputHorizontal(); CalcAlongAxis(0, true); }
///<summary> /// Called by the layout system. Also see ILayoutElement ///</summary> publicoverridevoidCalculateLayoutInputVertical() { CalcAlongAxis(1, true); }
///<summary> /// Called by the layout system. Also see ILayoutElement ///</summary> publicoverridevoidSetLayoutHorizontal() { SetChildrenAlongAxis(0, true); }
///<summary> /// Called by the layout system. Also see ILayoutElement ///</summary> publicoverridevoidSetLayoutVertical() { SetChildrenAlongAxis(1, true); } } }
using UnityEngine; using System.Collections.Generic;
namespaceUnityEngine.UI { [AddComponentMenu("Layout/Grid Layout Group", 152)] ///<summary> /// Layout class to arrange child elements in a grid format. ///</summary> ///<remarks> /// The GridLayoutGroup component is used to layout child layout elements in a uniform grid where all cells have the same size. The size and the spacing between cells is controlled by the GridLayoutGroup itself. The children have no influence on their sizes. ///</remarks> publicclassGridLayoutGroup : LayoutGroup { ///<summary> /// Which corner is the starting corner for the grid. ///</summary> publicenum Corner { ///<summary> /// Upper Left corner. ///</summary> UpperLeft = 0, ///<summary> /// Upper Right corner. ///</summary> UpperRight = 1, ///<summary> /// Lower Left corner. ///</summary> LowerLeft = 2, ///<summary> /// Lower Right corner. ///</summary> LowerRight = 3 }
///<summary> /// The grid axis we are looking at. ///</summary> ///<remarks> /// As the storage is a [][] we make access easier by passing a axis. ///</remarks> publicenum Axis { ///<summary> /// Horizontal axis ///</summary> Horizontal = 0, ///<summary> /// Vertical axis. ///</summary> Vertical = 1 }
///<summary> /// Constraint type on either the number of columns or rows. ///</summary> publicenum Constraint { ///<summary> /// Don't constrain the number of rows or columns. ///</summary> Flexible = 0, ///<summary> /// Constrain the number of columns to a specified number. ///</summary> FixedColumnCount = 1, ///<summary> /// Constraint the number of rows to a specified number. ///</summary> FixedRowCount = 2 }
///<summary> /// Which corner should the first cell be placed in? ///</summary> public Corner startCorner { get { return m_StartCorner; } set { SetProperty(ref m_StartCorner, value); } }
///<summary> /// Which axis should cells be placed along first ///</summary> ///<remarks> /// When startAxis is set to horizontal, an entire row will be filled out before proceeding to the next row. When set to vertical, an entire column will be filled out before proceeding to the next column. ///</remarks> public Axis startAxis { get { return m_StartAxis; } set { SetProperty(ref m_StartAxis, value); } }
[SerializeField] protected Vector2 m_CellSize = new Vector2(100, 100);
///<summary> /// The size to use for each cell in the grid. ///</summary> public Vector2 cellSize { get { return m_CellSize; } set { SetProperty(ref m_CellSize, value); } }
///<summary> /// The spacing to use between layout elements in the grid on both axises. ///</summary> public Vector2 spacing { get { return m_Spacing; } set { SetProperty(ref m_Spacing, value); } }
///<summary> /// Which constraint to use for the GridLayoutGroup. ///</summary> ///<remarks> /// Specifying a constraint can make the GridLayoutGroup work better in conjunction with a [[ContentSizeFitter]] component. When GridLayoutGroup is used on a RectTransform with a manually specified size, there's no need to specify a constraint. ///</remarks> public Constraint constraint { get { return m_Constraint; } set { SetProperty(ref m_Constraint, value); } }
///<summary> /// How many cells there should be along the constrained axis. ///</summary> publicint constraintCount { get { return m_ConstraintCount; } set { SetProperty(ref m_ConstraintCount, Mathf.Max(1, value)); } }
///<summary> /// Called by the layout system to calculate the horizontal layout size. /// Also see ILayoutElement ///</summary> publicoverridevoidCalculateLayoutInputHorizontal() { base.CalculateLayoutInputHorizontal();
///<summary> /// Called by the layout system /// Also see ILayoutElement ///</summary> publicoverridevoidSetLayoutHorizontal() { SetCellsAlongAxis(0); }
///<summary> /// Called by the layout system /// Also see ILayoutElement ///</summary> publicoverridevoidSetLayoutVertical() { SetCellsAlongAxis(1); }
privatevoidSetCellsAlongAxis(int axis) { // Normally a Layout Controller should only set horizontal values when invoked for the horizontal axis // and only vertical values when invoked for the vertical axis. // However, in this case we set both the horizontal and vertical position when invoked for the vertical axis. // Since we only set the horizontal position and not the size, it shouldn't affect children's layout, // and thus shouldn't break the rule that all horizontal layout must be calculated before all vertical layout. var rectChildrenCount = rectChildren.Count; if (axis == 0) { // Only set the sizes when invoked for horizontal axis, not the positions.
for (int i = 0; i < rectChildrenCount; i++) { RectTransform rect = rectChildren[i];
///<summary> /// Constraint type on either the number of columns or rows. ///</summary> publicenum Constraint { ///<summary> /// Don't constrain the number of rows or columns. ///</summary> Flexible = 0, ///<summary> /// Constrain the number of columns to a specified number. ///</summary> FixedColumnCount = 1, ///<summary> /// Constraint the number of rows to a specified number. ///</summary> FixedRowCount = 2 }
枚举
值
作用
Corner
UpperLeft / UpperRight / LowerLeft / LowerRight
网格从哪个角落开始排列
Axis
Horizontal / Vertical
先沿哪个轴填充(先填满一行再换行,还是先填满一列再换列)
Constraint
Flexible / FixedColumnCount / FixedRowCount
列数/行数是否固定
配置字段
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
[SerializeField] protected Corner m_StartCorner = Corner.UpperLeft; public Corner startCorner { get { return m_StartCorner; } set { SetProperty(ref m_StartCorner, value); } }
[SerializeField] protected Axis m_StartAxis = Axis.Horizontal; public Axis startAxis { get { return m_StartAxis; } set { SetProperty(ref m_StartAxis, value); } }
[SerializeField] protected Vector2 m_CellSize = new Vector2(100, 100); public Vector2 cellSize { get { return m_CellSize; } set { SetProperty(ref m_CellSize, value); } }
[SerializeField] protected Vector2 m_Spacing = Vector2.zero; public Vector2 spacing { get { return m_Spacing; } set { SetProperty(ref m_Spacing, value); } }
[SerializeField] protected Constraint m_Constraint = Constraint.Flexible; public Constraint constraint { get { return m_Constraint; } set { SetProperty(ref m_Constraint, value); } }
这段是修复 case 1345471——保证约束的列数/行数始终被遵守。某些边界情况下(子元素数较少、起始轴和约束方向交叉),直接按 i % cellsPerMainAxis 算位置会导致最后一行/列没有填满约束数量。childrenToMove 算的是“需要额外挪到前面”的子元素数量,在阶段 F 里用于特殊定位。
namespaceUnityEngine.UI { [AddComponentMenu("Layout/Content Size Fitter", 141)] [ExecuteAlways] [RequireComponent(typeof(RectTransform))] ///<summary> /// Resizes a RectTransform to fit the size of its content. ///</summary> ///<remarks> /// The ContentSizeFitter can be used on GameObjects that have one or more ILayoutElement components, such as Text, Image, HorizontalLayoutGroup, VerticalLayoutGroup, and GridLayoutGroup. ///</remarks> publicclassContentSizeFitter : UIBehaviour, ILayoutSelfController { ///<summary> /// The size fit modes avaliable to use. ///</summary> publicenum FitMode { ///<summary> /// Don't perform any resizing. ///</summary> Unconstrained, ///<summary> /// Resize to the minimum size of the content. ///</summary> MinSize, ///<summary> /// Resize to the preferred size of the content. ///</summary> PreferredSize }
///<summary> /// The fit mode to use to determine the width. ///</summary> public FitMode horizontalFit { get { return m_HorizontalFit; } set { if (SetPropertyUtility.SetStruct(ref m_HorizontalFit, value)) SetDirty(); } }
///<summary> /// The fit mode to use to determine the height. ///</summary> public FitMode verticalFit { get { return m_VerticalFit; } set { if (SetPropertyUtility.SetStruct(ref m_VerticalFit, value)) SetDirty(); } }
// Set size to min or preferred size if (fitting == FitMode.MinSize) rectTransform.SetSizeWithCurrentAnchors((RectTransform.Axis)axis, LayoutUtility.GetMinSize(m_Rect, axis)); else rectTransform.SetSizeWithCurrentAnchors((RectTransform.Axis)axis, LayoutUtility.GetPreferredSize(m_Rect, axis)); }
///<summary> /// Calculate and apply the horizontal component of the size to the RectTransform ///</summary> publicvirtualvoidSetLayoutHorizontal() { m_Tracker.Clear(); HandleSelfFittingAlongAxis(0); }
///<summary> /// Calculate and apply the vertical component of the size to the RectTransform ///</summary> publicvirtualvoidSetLayoutVertical() { HandleSelfFittingAlongAxis(1); }
protectedvoidSetDirty() { if (!IsActive()) return;
publicenumFitMode { ///<summary> /// Don't perform any resizing. ///</summary> Unconstrained, ///<summary> /// Resize to the minimum size of the content. ///</summary> MinSize, ///<summary> /// Resize to the preferred size of the content. ///</summary> PreferredSize }
[SerializeField] protected FitMode m_HorizontalFit = FitMode.Unconstrained; ///<summary> /// The fit mode to use to determine the width. ///</summary> public FitMode horizontalFit { get { return m_HorizontalFit; } set { if (SetPropertyUtility.SetStruct(ref m_HorizontalFit, value)) SetDirty(); } }
[SerializeField] protected FitMode m_VerticalFit = FitMode.Unconstrained; ///<summary> /// The fit mode to use to determine the height. ///</summary> public FitMode verticalFit { get { return m_VerticalFit; } set { if (SetPropertyUtility.SetStruct(ref m_VerticalFit, value)) SetDirty(); } }