在开发UI对话框的时候总是遇到需要自适应大小的对话框。
单行的情况下水平伸缩,多行的情况下竖直伸缩,并可以实现动态伸缩
思路:主要是通过UGUI的text组件和Content Size Fitter组件实现
使用方法:该脚本放到text组件上即可,将text变量给到需要实现自动伸缩的对话框,在text物体上挂在Content Size Fitter组件,并将初始参数都改为Preferred Size
public class smartbubble : MonoBehaviour
{
[SerializeField] private float maxWidth;
[SerializeField] private GameObject text;
private int maxTextLength=-1;
void Start()
{
text.GetComponent<Text>().horizontalOverflow = HorizontalWrapMode.Wrap;
text.GetComponent<ContentSizeFitter>().horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
if (text.GetComponent<RectTransform>().rect.width > maxWidth)
maxWidth = text.GetComponent<RectTransform>().rect.width;
text.GetComponent<Text>().RegisterDirtyVerticesCallback(() =>
{
Debug.Log(maxTextLength);
//通过换行长度 记录换行字符数
if (maxTextLength == -1)
{
if (text.GetComponent<RectTransform>().rect.width > maxWidth)
{
maxTextLength = text.GetComponent<Text>().text.Length;
}
LayoutRebuilder.ForceRebuildLayoutImmediate(text.GetComponent<RectTransform>());
return;
}
//如果未达到换行字符数 水平展开
if (text.GetComponent<Text>().text.Length < maxTextLength)
{
text.GetComponent<ContentSizeFitter>().horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
}
//达到换行数 竖直展开
else if(text.GetComponent<Text>().text.Length > maxTextLength)
{
text.GetComponent<ContentSizeFitter>().horizontalFit = ContentSizeFitter.FitMode.Unconstrained;
}
LayoutRebuilder.ForceRebuildLayoutImmediate(text.GetComponent<RectTransform>());
});
}
}
单行效果
多行效果