本文章参考 雨松大神的文章 稍加修改
添加应用
using FitMode = UnityEngine.UI.ContentSizeFitter.FitMode;
两个核心方法 ( 把挂有Content Size Fitter 组件的物体当参数传入)
//立即获取ContentSizeFitter的区域public Vector2 GetPreferredSize(GameObject obj)
{
LayoutRebuilder.ForceRebuildLayoutImmediate(obj.GetComponent <RectTransform>());
return new Vector2(HandleSelfFittingAlongAxis(0,obj), HandleSelfFittingAlongAxis(1,obj));
}
//获取宽和高
private float HandleSelfFittingAlongAxis(int axis,GameObject obj)
{
FitMode fitting = (axis == 0 ? obj.GetComponent<ContentSizeFitter>().horizontalFit : obj.GetComponent<ContentSizeFitter>().verticalFit);
if (fitting == FitMode.MinSize)
{
return LayoutUtility.GetMinSize(obj.GetComponent<RectTransform>(), axis);
}
else
{
return LayoutUtility.GetPreferredSize(obj.GetComponent<RectTransform>(), axis);
}
}