Unity Text文字超过长度显示为省略号

亲测可用

有这样一个需求,文字超过多少字,或者超过几排,就显示为省略号,这样既可以让用户看到内容,如果内容过多,也不会太复杂繁琐,特别是在聊天中最能体现它的优势,效果如下图:

 

思路:使用TextGenerator,预先得到文本框能显示字数,行数,高度,宽度等,用于逻辑开发。

  • 获取宽高,TextGenerator为Unity文字生成类,text.GetGenerationSettings(vertec2 param)得到当前text的生成配置(字号,字体,间距等),参数意思:生成器将尝试使文本适合此范围。将文本生成到这个宽高的text中去,它会决定生成之后行、列数。例如高度比较小(20左右)那么生成之后就只有一行。 官方文档UnityEngine.TextGenerationSettings - Unity 脚本 API
  • GetPreferredHeightGetPreferredHeight这两个方法,如果传入单个字,输出就是单个字的宽高;如果传入长串字符,则是长串总宽高,注意:在刚才传入的范围内。
  • generateSetting.scaleFactor这里为什么要相除呢,因为它是文本的缩放因子。在 Text 位于 Canvas 上并且画布缩放时非常有用。相除之后就得到正确的宽高了。

完整代码:

    TextGenerator generator = new TextGenerator();
    TextGenerationSettings generateSetting = new TextGenerationSettings();
    public int col = 2; //从几排开始省略号...
    private float singleHeight = 0;
    private RectTransform rectTransform;
    private Text text_com;
    public void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
        text_com = GetComponent<Text>();
    }

    public void SetTextWithEllipsis(string _str)
    {
        text_com.text = _str;
        generateSetting = text_com.GetGenerationSettings(new Vector2(rectTransform.rect.width, 300));
        singleHeight = generator.GetPreferredHeight(text_com.text, generateSetting);
        generator.Populate(text_com.text, generateSetting); //生成文本,得到在范围内的行数,是否超过规定行数2
        singleHeight = singleHeight / generator.lineCount / generateSetting.scaleFactor;

        var updatedText = text_com.text;
        if (generator.lineCount == 1)rectTransform.sizeDelta = new Vector2(rectTransform.rect.width, singleHeight);
        if (generator.lineCount >= col)
        {
            //大于2行之后,自动调整文本框大小
            rectTransform.sizeDelta = new Vector2(rectTransform.rect.width, singleHeight * 2);
            generateSetting = text_com.GetGenerationSettings(rectTransform.rect.size);
            //再次生成文字,得到characterCountVisible,即两行的宽度能显示多少个字
            generator.Populate(text_com.text, generateSetting);

            var characterCountVisible = generator.characterCountVisible;
            if (text_com.text.Length > characterCountVisible) //超过两行的字数,把后面的字数截取,替换成省略号......
            {
                updatedText = text_com.text.Substring(0, characterCountVisible - 3);
                updatedText += "......";
            }
        }
        text_com.text = updatedText;
    }

猜你喜欢

转载自blog.csdn.net/Ling_SevoL_Y/article/details/126263397