- Home /
How to get the current "best fit" size of a Text component?
So the title is the question. I'm using the new UI system, and i cant seem to get the current size of the font when it is in "best fit" mode.
I tried to get the property "fontSize", however, that size is not the currect one if its in the best fit mode.
Answer by Assassinbeast · Sep 03, 2014 at 08:25 PM
Alright, i just figured it out myself. Its in Text.cachedTextGenerator.fontSizeUsedForBestFit
I just want to add that in order to make this work i needed to get that size at the end of the frame like this.
void Start()
{
StartCoroutine("SetSize");
}
IEnumerator SetSize()
{
yield return new WaitForEndOfFrame();
int sizeAux = texto.cachedTextGenerator.fontSizeUsedForBestFit;
//Do staff
}
Answer by LocalDude · Mar 30, 2017 at 04:14 PM
if you need to get the size the same frame that you set it you can use.
text.text = "The text you want";
text.cachedTextGenerator.Invalidate();
Vector2 size = (text.transform as RectTransform).rect.size;
TextGenerationSettings tempSettings = text.GetGenerationSettings(size);
tempSettings.scaleFactor = 1;//dont know why but if I dont set it to 1 it returns a font that is to small.
if(!text.cachedTextGenerator.Populate(textVal, tempSettings))
Debug.LogError("Failed to generate fit size");
text.resizeTextMaxSize = text.cachedTextGenerator.fontSizeUsedForBestFit;
Answer by psyydack · Sep 22, 2014 at 10:02 PM
Here's my trick:
private int mFontMaxAtual;
public int mBuggedSize;
public int mCorrectFont;
public int fontSizeAtual;
// Use this for initialization
void Awake ()
{
mFontMaxAtual = GetComponent<Text> ().resizeTextMaxSize;
}
// Update is called once per frame
void Update ()
{
fontSizeAtual = GetComponent<Text> ().cachedTextGenerator.fontSizeUsedForBestFit;
if (fontSizeAtual == mBuggedSize) {
GetComponent<Text> ().resizeTextMaxSize = mCorrectFont;
} else {
GetComponent<Text> ().resizeTextMaxSize = mFontMaxAtual;
}
print (GetComponent<Text> ().cachedTextGenerator.fontSizeUsedForBestFit);
}
Your answer
Follow this Question
Related Questions
Figure out the pixel size of a character 1 Answer
Text blurred: uGUI 4.6 9 Answers
Replacing transparency of text with a solid color? 1 Answer
Text Appearance Glitch in Unity UI, 5.3 0 Answers
How to measure the width of a string? 0 Answers