|
@@ -0,0 +1,99 @@
|
|
|
+using System.Collections;
|
|
|
+using System.Collections.Generic;
|
|
|
+
|
|
|
+using UnityEngine;
|
|
|
+using UnityEngine.UI;
|
|
|
+using UnityEngine.Events;
|
|
|
+
|
|
|
+public class BestfitText : Text
|
|
|
+{
|
|
|
+ #region
|
|
|
+
|
|
|
+ protected string FormerText;
|
|
|
+
|
|
|
+ #endregion
|
|
|
+
|
|
|
+ protected void Update()
|
|
|
+ {
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ protected override void OnPopulateMesh(VertexHelper toFill)
|
|
|
+ {
|
|
|
+ base.OnPopulateMesh(toFill);
|
|
|
+
|
|
|
+ if (text != FormerText)
|
|
|
+ {
|
|
|
+ FormerText = text;
|
|
|
+
|
|
|
+ StartCoroutine(DelayCall(Bestfit, 2));
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ protected void Bestfit()
|
|
|
+ {
|
|
|
+ TextGenerationSettings textGenerationSettings = GetGenerationSettings(rectTransform.rect.size);
|
|
|
+
|
|
|
+ bool shrink = false;
|
|
|
+ bool expand = false;
|
|
|
+
|
|
|
+ int antiCrush = 0;
|
|
|
+
|
|
|
+ while (true)
|
|
|
+ {
|
|
|
+ antiCrush++;
|
|
|
+
|
|
|
+ if (antiCrush > 100)
|
|
|
+ {
|
|
|
+ Debug.LogError("Crush");
|
|
|
+
|
|
|
+ break;
|
|
|
+ }
|
|
|
+
|
|
|
+ int preferredLineHeight = Mathf.CeilToInt(cachedTextGenerator.GetPreferredHeight("1", textGenerationSettings));
|
|
|
+
|
|
|
+ int preferredLineCount = Mathf.CeilToInt(cachedTextGenerator.GetPreferredHeight(text, textGenerationSettings)) / preferredLineHeight;
|
|
|
+
|
|
|
+ int bestHeight = preferredLineHeight * preferredLineCount;
|
|
|
+
|
|
|
+ if (bestHeight > rectTransform.rect.size.y)
|
|
|
+ {
|
|
|
+ textGenerationSettings.fontSize--;
|
|
|
+
|
|
|
+ if (expand)
|
|
|
+ {
|
|
|
+ break;
|
|
|
+ }
|
|
|
+
|
|
|
+ shrink = true;
|
|
|
+ }
|
|
|
+ else if (bestHeight < rectTransform.rect.size.y)
|
|
|
+ {
|
|
|
+ if (shrink)
|
|
|
+ {
|
|
|
+ break;
|
|
|
+ }
|
|
|
+
|
|
|
+ textGenerationSettings.fontSize++;
|
|
|
+
|
|
|
+ expand = true;
|
|
|
+ }
|
|
|
+ else if (bestHeight.Equal(rectTransform.rect.size.y))
|
|
|
+ {
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ fontSize = textGenerationSettings.fontSize;
|
|
|
+ }
|
|
|
+
|
|
|
+ protected IEnumerator DelayCall(UnityAction unityAction, int frame)
|
|
|
+ {
|
|
|
+ while (frame-- > 0)
|
|
|
+ {
|
|
|
+ yield return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ unityAction.SafeInvoke();
|
|
|
+ }
|
|
|
+}
|