Unity3d让GridLayoutGroup按照子物体的数量自动调整宽高

    /// <summary>
    /// 设置GridLayoutGroup的宽高
    /// </summary>
    /// <param name="grid">需要调整宽高的GridLayoutGroup</param>
    private void AutoGridLayoutSize(GridLayoutGroup grid)
    {
        int num = grid.constraintCount;//每行/列Cell约束的个数
        int k = (grid.transform.childCount + num - 1) / num;
        float value;
        RectTransform.Axis axis;
        switch (grid.constraint)
        {
            case GridLayoutGroup.Constraint.FixedColumnCount:
                value = k * grid.cellSize.y;//列数乘以Cell的高度
                value += (k - 1) * grid.spacing.y;//每列之间有间隔
                value += grid.padding.top + grid.padding.bottom;//上下间隔
                axis = RectTransform.Axis.Vertical;
                break;
            case GridLayoutGroup.Constraint.FixedRowCount:
                value = k * grid.cellSize.x;//行数乘以Cell的高度
                value += (k - 1) * grid.spacing.x;//每行之间有间隔
                value += grid.padding.left + grid.padding.right;//左右间隔
                axis = RectTransform.Axis.Horizontal;
                break;
            default:
                Debug.LogError(grid.name + "的约束为:Flexibl!");
                return;
        }
        (grid.transform as RectTransform).SetSizeWithCurrentAnchors(axis, value);
    }
posted @ 2021-09-01 15:47  蓝闪  阅读(1868)  评论(0编辑  收藏  举报