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


    亲测可用

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

     

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

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

    完整代码:

    1. TextGenerator generator = new TextGenerator();
    2. TextGenerationSettings generateSetting = new TextGenerationSettings();
    3. public int col = 2; //从几排开始省略号...
    4. private float singleHeight = 0;
    5. private RectTransform rectTransform;
    6. private Text text_com;
    7. public void Awake()
    8. {
    9. rectTransform = GetComponent();
    10. text_com = GetComponent();
    11. }
    12. public void SetTextWithEllipsis(string _str)
    13. {
    14. text_com.text = _str;
    15. generateSetting = text_com.GetGenerationSettings(new Vector2(rectTransform.rect.width, 300));
    16. singleHeight = generator.GetPreferredHeight(text_com.text, generateSetting);
    17. generator.Populate(text_com.text, generateSetting); //生成文本,得到在范围内的行数,是否超过规定行数2
    18. singleHeight = singleHeight / generator.lineCount / generateSetting.scaleFactor;
    19. var updatedText = text_com.text;
    20. if (generator.lineCount == 1)rectTransform.sizeDelta = new Vector2(rectTransform.rect.width, singleHeight);
    21. if (generator.lineCount >= col)
    22. {
    23. //大于2行之后,自动调整文本框大小
    24. rectTransform.sizeDelta = new Vector2(rectTransform.rect.width, singleHeight * 2);
    25. generateSetting = text_com.GetGenerationSettings(rectTransform.rect.size);
    26. //再次生成文字,得到characterCountVisible,即两行的宽度能显示多少个字
    27. generator.Populate(text_com.text, generateSetting);
    28. var characterCountVisible = generator.characterCountVisible;
    29. if (text_com.text.Length > characterCountVisible) //超过两行的字数,把后面的字数截取,替换成省略号......
    30. {
    31. updatedText = text_com.text.Substring(0, characterCountVisible - 3);
    32. updatedText += "......";
    33. }
    34. }
    35. text_com.text = updatedText;
    36. }

  • 相关阅读:
    @RequestMapping 注解以及其它使用方式
    Grafana Panel组件跳转、交互实现
    Android悬浮窗框架
    【7.25考研数据结构记录】树与二叉树
    代码随想录day39 || 动态规划 || 不同路径
    算法课实验报告解析(4班供参考)
    list容器 常用 API操作
    【SOLIDWORKS学习笔记】装配体基础操作
    神经网络(十)激活函数DLC
    钡铼BL124PN:简单快速转换Profinet到Ethernet/IP
  • 原文地址:https://blog.csdn.net/Ling_SevoL_Y/article/details/126263397