BestfitText.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. protected string FormerText;
  10. #endregion
  11. protected void Update()
  12. {
  13. }
  14. protected override void OnPopulateMesh(VertexHelper toFill)
  15. {
  16. base.OnPopulateMesh(toFill);
  17. if (text != FormerText)
  18. {
  19. FormerText = text;
  20. StartCoroutine(DelayCall(Bestfit, 2));
  21. }
  22. }
  23. protected void Bestfit()
  24. {
  25. TextGenerationSettings textGenerationSettings = GetGenerationSettings(rectTransform.rect.size);
  26. bool shrink = false;
  27. bool expand = false;
  28. int antiCrush = 0;
  29. while (true)
  30. {
  31. antiCrush++;
  32. if (antiCrush > 100)
  33. {
  34. Debug.LogError("Crush");
  35. break;
  36. }
  37. int preferredLineHeight = Mathf.CeilToInt(cachedTextGenerator.GetPreferredHeight("1", textGenerationSettings));
  38. int preferredLineCount = Mathf.CeilToInt(cachedTextGenerator.GetPreferredHeight(text, textGenerationSettings)) / preferredLineHeight;
  39. int bestHeight = preferredLineHeight * preferredLineCount;
  40. if (bestHeight > rectTransform.rect.size.y)
  41. {
  42. textGenerationSettings.fontSize--;
  43. if (expand)
  44. {
  45. break;
  46. }
  47. shrink = true;
  48. }
  49. else if (bestHeight < rectTransform.rect.size.y)
  50. {
  51. if (shrink)
  52. {
  53. break;
  54. }
  55. textGenerationSettings.fontSize++;
  56. expand = true;
  57. }
  58. else if (bestHeight.Equal(rectTransform.rect.size.y))
  59. {
  60. break;
  61. }
  62. }
  63. fontSize = textGenerationSettings.fontSize;
  64. }
  65. protected IEnumerator DelayCall(UnityAction unityAction, int frame)
  66. {
  67. while (frame-- > 0)
  68. {
  69. yield return null;
  70. }
  71. unityAction.SafeInvoke();
  72. }
  73. }