首页 > 其他分享> > Unity使用Font.GetCharacterInfo 和 Font.RequestCharactersInTexture获取UnityEngine.UI.Text文本中每个字符的宽度信息
Unity使用Font.GetCharacterInfo 和 Font.RequestCharactersInTexture获取UnityEngine.UI.Text文本中每个字符的宽度信息
作者:互联网
using UnityEngine;
using UnityEngine.UI;
public class FontTest : MonoBehaviour
{
void Start()
{
Test();
}
void Test()
{
string str = GetComponent<Text>().text;
Font font = GetComponent<Text>().font;
//此处请求生成字符信息
font.RequestCharactersInTexture(str, GetComponent<Text>().fontSize, FontStyle.Normal);
char[] charArr = str.ToCharArray();
int totalWidth = 0;
CharacterInfo info;
for(int i = 0; i < charArr.Length; i++)
{
char c = charArr[i];
//此处读取字符信息,需要在前面的RequestCharactersInTexture函数里调用过
//注意,size和style这两个参数(第3,4个)要和RequestCharactersInTexture的对应参数(第2,3个)保持一致,否则返回false,获取不到字符信息,info里的数据全为0
bool getCharacterInfoSucc = font.GetCharacterInfo(c, out info, GetComponent<Text>().fontSize,FontStyle.Normal);
if (getCharacterInfoSucc)
{
totalWidth += info.advance;
Debug.Log("glyphHeight = " + info.glyphHeight.ToString());
}
else
{
Debug.LogError("getCharacterInfo failed : " + c);
}
}
//这里打印的就是Text组件的宽度了
Debug.Log("总width为 " + totalWidth.ToString());
}
}
标签:info,RequestCharactersInTexture,UnityEngine,font,GetComponent,totalWidth,Font 来源: https://www.cnblogs.com/Jukka/p/16600646.html