UGUI-计算子项在容器中的Bounds

作者:追风剑情 发布于:2019-7-5 10:06 分类:Unity3d

示例


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class UGUITool
{
    /// <summary>
    /// 计算子项在容器中的Bounds(相对于Container的锚点)
    /// </summary>
    /// <param name="container">可以不是直接父容器</param>
    /// <param name="child"></param>
    /// <returns></returns>
    public static Bounds CalculateBounds(RectTransform container, RectTransform child)
    {
        Vector3[] corners = new Vector3[4];
        child.GetWorldCorners(corners);

        Matrix4x4 containerWorldToLocalMatrix = container.worldToLocalMatrix;
        var vMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
        var vMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);

        for (int j = 0; j < 4; j++)
        {
            Vector3 v = containerWorldToLocalMatrix.MultiplyPoint3x4(corners[j]);
            vMin = Vector3.Min(v, vMin);
            vMax = Vector3.Max(v, vMax);
        }

        Bounds bounds = new Bounds(vMin, Vector3.zero);
        bounds.Encapsulate(vMax);

        return bounds;
    }

    // 计算RectTransform的Bounds
    public static Bounds CalculateBounds(RectTransform rectTransform)
    {
        return new Bounds(rectTransform.rect.center, rectTransform.rect.size);
    }
}


标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号