Unity Text大小随文字内容多少而变化

using UnityEngine;
using UnityEngine.UI;

public class AutoSizeText
{
    private static AutoSizeText instance;
    public static AutoSizeText Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new AutoSizeText();
            }
            return instance;
        }
    }


    /// <summary>
    /// 通过Text文本的内容多少,进行缩放文本框大小
    /// </summary>
    /// <param name="text">需要控制的text</param>
    /// <param name="txt">文本</param>

    public void LoadAutoSizeText(Text text, string txt)
    {
        text.text = txt;
        RectTransform rectTransform = text.GetComponent<RectTransform>();

        int textLength = text.text.Length;
        float preferredHeight = text.preferredHeight; //通过text.preferredHeight获取理想text高度值
        rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, preferredHeight);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_38513810/article/details/138131385