BestfitText.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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. public int VerticalMinSize = 1;
  10. public int VerticalMaxSize = 29;
  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. while (true)
  32. {
  33. antiCrush++;
  34. if (antiCrush > 1000)
  35. {
  36. Debug.LogError("Crush");
  37. break;
  38. }
  39. float bestHeight = cachedTextGenerator.GetPreferredHeight(text, textGenerationSettings);
  40. if (bestHeight > rectTransform.rect.size.y*canvas.scaleFactor)
  41. {
  42. textGenerationSettings.fontSize--;
  43. if (textGenerationSettings.fontSize < VerticalMinSize)
  44. {
  45. textGenerationSettings.fontSize = VerticalMinSize;
  46. break;
  47. }
  48. else if (textGenerationSettings.fontSize > VerticalMaxSize)
  49. {
  50. textGenerationSettings.fontSize = VerticalMaxSize;
  51. }
  52. else
  53. {
  54. if (expand)
  55. {
  56. break;
  57. }
  58. else
  59. {
  60. shrink = true;
  61. }
  62. }
  63. }
  64. else if (bestHeight < rectTransform.rect.size.y * canvas.scaleFactor)
  65. {
  66. if (shrink)
  67. {
  68. break;
  69. }
  70. textGenerationSettings.fontSize++;
  71. if (textGenerationSettings.fontSize < VerticalMinSize)
  72. {
  73. textGenerationSettings.fontSize = VerticalMinSize;
  74. }
  75. else if (textGenerationSettings.fontSize >= VerticalMaxSize)
  76. {
  77. textGenerationSettings.fontSize = VerticalMaxSize;
  78. break;
  79. }
  80. else
  81. {
  82. expand = true;
  83. }
  84. }
  85. else if (bestHeight.Equal(rectTransform.rect.size.y * canvas.scaleFactor))
  86. {
  87. break;
  88. }
  89. }
  90. fontSize = textGenerationSettings.fontSize;
  91. }
  92. protected IEnumerator DelayCall(UnityAction unityAction, int frame)
  93. {
  94. while (frame-- > 0)
  95. {
  96. yield return null;
  97. }
  98. unityAction.SafeInvoke();
  99. }
  100. }