BestfitText.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.Events;
  6. public class BestfitText : Text
  7. {
  8. #region
  9. private int VerticalMinSize;
  10. private int VerticalMaxSize;
  11. protected string FormerText;
  12. #endregion
  13. protected void Update()
  14. {
  15. }
  16. protected override void OnPopulateMesh(VertexHelper toFill)
  17. {
  18. base.OnPopulateMesh(toFill);
  19. if (text != FormerText)
  20. {
  21. FormerText = text;
  22. StartCoroutine(DelayCall(Bestfit, 1));
  23. }
  24. }
  25. protected void Bestfit()
  26. {
  27. TextGenerationSettings textGenerationSettings = GetGenerationSettings(rectTransform.rect.size);
  28. bool shrink = false;
  29. bool expand = false;
  30. int antiCrush = 0;
  31. VerticalMinSize = 1;
  32. VerticalMaxSize = 29;
  33. while (true)
  34. {
  35. antiCrush++;
  36. if (antiCrush > 1000)
  37. {
  38. Debug.LogError("Crush");
  39. break;
  40. }
  41. float bestHeight = cachedTextGenerator.GetPreferredHeight(text, textGenerationSettings);
  42. if (bestHeight > rectTransform.rect.size.y*canvas.scaleFactor)
  43. {
  44. textGenerationSettings.fontSize--;
  45. if (textGenerationSettings.fontSize < VerticalMinSize)
  46. {
  47. textGenerationSettings.fontSize = VerticalMinSize;
  48. break;
  49. }
  50. else if (textGenerationSettings.fontSize > VerticalMaxSize)
  51. {
  52. textGenerationSettings.fontSize = VerticalMaxSize;
  53. }
  54. else
  55. {
  56. if (expand)
  57. {
  58. break;
  59. }
  60. else
  61. {
  62. shrink = true;
  63. }
  64. }
  65. }
  66. else if (bestHeight < rectTransform.rect.size.y * canvas.scaleFactor)
  67. {
  68. if (shrink)
  69. {
  70. break;
  71. }
  72. textGenerationSettings.fontSize++;
  73. if (textGenerationSettings.fontSize < VerticalMinSize)
  74. {
  75. textGenerationSettings.fontSize = VerticalMinSize;
  76. }
  77. else if (textGenerationSettings.fontSize >= VerticalMaxSize)
  78. {
  79. textGenerationSettings.fontSize = VerticalMaxSize;
  80. break;
  81. }
  82. else
  83. {
  84. expand = true;
  85. }
  86. }
  87. else if (bestHeight.Equal(rectTransform.rect.size.y * canvas.scaleFactor))
  88. {
  89. break;
  90. }
  91. }
  92. fontSize = textGenerationSettings.fontSize;
  93. }
  94. protected IEnumerator DelayCall(UnityAction unityAction, int frame)
  95. {
  96. while (frame-- > 0)
  97. {
  98. yield return null;
  99. }
  100. unityAction.SafeInvoke();
  101. }
  102. }