unity C# ,获取文本宽度/字体字符宽度 [英] Unity C# , get text width / font character width

查看:87
本文介绍了unity C# ,获取文本宽度/字体字符宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 C# 统一获取文本的宽度.

I want to get the width of a text in unity using C# .

这就是我想要做的.

int GetWidthOfMessage(string message)
{
    int totalLength = 0;

    Font font = text.font; //text is my UI text
    CharacterInfo characterInfo = new CharacterInfo();

    char[] arr = message.ToCharArray();

    foreach (char c in arr)
    {
        font.GetCharacterInfo(c, out characterInfo, text.fontSize);
        totalLength += characterInfo.advance;
    }

    return totalLength;
}

但是 font.GetCharacterInfo(...) 返回 false 并且 characterInfo.advance 对于任何字符都是 0 .

But font.GetCharacterInfo(...) returns false and characterInfo.advance is 0 for any character .

推荐答案

除了您原来的问题.按照你做这一切的原因(根据文本内容扩展文本框).

Apart from your original question. Following the reason you are doing all this (expanding text box according to text content).

您可以在文本对象上使用 Content Size Fitter 组件并设置Horizo​​ntal Fit 属性为 Preferred Size.这将解决您的问题.

You can use Content Size Fitter component on your text object and set Horizontal Fit property to Preferred Size. And this will solve your problem.

更新:

添加 Layout Element 组件并将首选宽度值设置为 500例如,将文本的 Horizo​​ntal Overflow 属性设置为 Wrap.这肯定会奏效.

Add Layout Element component as well and set preferred width value to 500 for example and set Horizontal Overflow property of text to Wrap. This will work fo sure.

这篇关于unity C# ,获取文本宽度/字体字符宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆