Unity3d中GridLayoutGroup组件的自适应宽高
Unity中常用的布局自动排列组件:
GridLayoutGroup
、
VerticalLayoutGroup
和
HorizontalLayoutGroup
。其中后面两个有比较好的自适应能力,而
GridLayoutGroup
,则没有,需要我们自己变相相关代码:
- 高:
/// <summary>
/// 设置父节点的高度
/// </summary>
/// <param name="num">每行Cell的个数</param>
private void SetGridHeight(int num)
{
float childCount = m_parent.childCount;//获得Layout Group子物体个数
int k = (int)(childCount + num - 1) / num;
float height = k * m_grid.cellSize.y;//行数乘以Cell的高度
height += (k - 1) * m_grid.spacing.y;//每行之间有间隔
height += m_grid.padding.top + m_grid.padding.bottom;//上下间隔
m_parent.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
}
其中:
m_parent = parent;//RectTransform
m_grid = parent.GetComponent<GridLayoutGroup>();
- 宽:
/// <summary>
/// 设置父节点的宽度
/// </summary>
/// <param name="num">每列Cell的个数</param>
private void SetGridHeight(int num)
{
float childCount = m_parent.childCount;//获得Layout Group子物体个数
int k = (int)(childCount + num - 1) / num;
float width = k * m_grid.cellSize.x;//行数乘以Cell的宽度
width += (k - 1) * m_grid.spacing.x;//每列之间有间隔
width += m_grid.padding.left + m_grid.padding.right;//左右间隔
m_parent.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width);
}
为了方便使用,将上面的两个函数进行合并后,便是下面的函数:
/// <summary>
/// 设置父节点(网格布局集团)的宽高
/// </summary>
/// <param name="childCount">获得Layout Group显示的子物体个数</param>
protected virtual void SetGrid(int childCount)
{
int num = m_grid.constraintCount;//每行/列Cell约束的个数
int k = (childCount + num - 1) / num;
float value;
RectTransform.Axis axis;
switch (m_grid.constraint)
{
case GridLayoutGroup.Constraint.FixedColumnCount:
value = k * m_grid.cellSize.y;//列数乘以Cell的高度
value += (k - 1) * m_grid.spacing.y;//每列之间有间隔
value += m_grid.padding.top + m_grid.padding.bottom;//上下间隔
axis = RectTransform.Axis.Vertical;
break;
case GridLayoutGroup.Constraint.FixedRowCount:
value = k * m_grid.cellSize.x;//行数乘以Cell的高度
value += (k - 1) * m_grid.spacing.x;//每行之间有间隔
value += m_grid.padding.left + m_grid.padding.right;//左右间隔
axis = RectTransform.Axis.Horizontal;
break;
default:
Debug.LogError(m_grid.name + "的约束为:Flexibl!");
return;
}
m_parent.SetSizeWithCurrentAnchors(axis, value);
}