123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- 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();
- }
- }
|