示例
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);
}
}