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