利用Unity UI 实现一个自动伸缩的对话框

在开发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>());
        });
    }

}

单行效果

多行效果 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值