游戏开发unity UGUI知识系列:计算单行文本的宽度

在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当做新文本的宽度)

经检验,两个方法获取的文本宽度是一样的。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值