BestfitText.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. float bestHeight = cachedTextGenerator.GetPreferredHeight(text, textGenerationSettings);
  38. if (bestHeight > rectTransform.rect.size.y)
  39. {
  40. textGenerationSettings.fontSize--;
  41. if (expand)
  42. {
  43. break;
  44. }
  45. shrink = true;
  46. }
  47. else if (bestHeight < rectTransform.rect.size.y)
  48. {
  49. if (shrink)
  50. {
  51. break;
  52. }
  53. textGenerationSettings.fontSize++;
  54. expand = true;
  55. }
  56. else if (bestHeight.Equal(rectTransform.rect.size.y))
  57. {
  58. break;
  59. }
  60. }
  61. fontSize = textGenerationSettings.fontSize;
  62. }
  63. protected IEnumerator DelayCall(UnityAction unityAction, int frame)
  64. {
  65. while (frame-- > 0)
  66. {
  67. yield return null;
  68. }
  69. unityAction.SafeInvoke();
  70. }
  71. }