在Text使用了ContentSizeFitter情况下,对text设置新的字符串后,如果我们想要在当前帧获取宽度时,通过RectTransform.sizeDelta.x获取的宽度经常是旧字符串时的长度。所以需要自行计算改变文本后text的宽度
下述代码参考:
public class TextContent : MonoBehaviour
{
public Text TxtCalcWidth;
private void FailGetTextWidthInCurFrame(Text text)
{
RectTransform rt = text.rectTransform;
float width = rt.sizeDelta.x;
Debug.Log("width = " + width.ToString());
}
private IEnumerator GetTextWidthInNextFrame(Text text)
{
yield return null;
RectTransform rt = text.rectTransform;
float width = rt.sizeDelta.x;
Debug.Log("width = " + width.ToString());
}
private void CalcTextWidth(Text text)
{
TextGenerator tg = text.cachedTextGeneratorForLayout;
TextGenerationSettings setting = text.GetGenerationSettings(Vector2.zero);
float width = tg.GetPreferredWidth(text.text, setting) / text.pixelsPerUnit;
Debug.Log("width = " + width.ToString());
}
public void OnBtnCalcWidthClick()
{
string text = "dsfasfs";
TxtCalcWidth.text = text;
//CalcTextWidth(TxtCalcWidth);
//StartCoroutine(GetTextWidthInNextFrame(TxtCalcWidth));
FailGetTextWidthInCurFrame(TxtCalcWidth);
}
}
有两种方式获取文本宽度:
CalcTextWidth为在当前帧计算新文本的宽度
GetTextWidthInNextFrame为下一帧获取文本的宽度(因为使用了layout,sizeDelta的值在一帧中的代码逻辑执行完后才会改变,所以可以在下一帧去获取sizeDelta当做新文本的宽度)
经检验,两个方法获取的文本宽度是一样的。