TextEllipsis.cs 905 B

123456789101112131415161718192021222324
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public static class TextEllipsis
  6. {
  7. //超框显示
  8. public static void SetTextWithEllipsis(this Text textComponent, string value) {
  9. TextGenerator generator = new TextGenerator();
  10. var settings = textComponent.GetGenerationSettings(textComponent.rectTransform.rect.size);
  11. generator.Populate(value, settings);
  12. var characterCountVisible = generator.characterCountVisible;
  13. var updatedText = value;
  14. if (value.Length > characterCountVisible)
  15. {
  16. updatedText = value.Substring(0, characterCountVisible);
  17. updatedText += "…";
  18. }
  19. //Debug.Log(value + ",文本宽度为:" + generator.GetPreferredWidth(value, settings)+",width:"+ textComponent.rectTransform.rect.width);
  20. textComponent.text = updatedText;
  21. }
  22. }