using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FetFont : MonoBehaviour
{
public Text text;
public GameObject go;
void Start ()
{
RectTransform rec = go.GetComponent<RectTransform>();
CalculateLengthOfText(text.GetComponent<Text>().text, text);
GetComponent<RectTransform>().sizeDelta = new Vector2(CalculateLengthOfText(text.GetComponent<Text>().text, text)/2f, GetComponent<RectTransform>().sizeDelta.y);
}
/// <summary>
/// 计算字符串在指定text控件中的长度
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
int CalculateLengthOfText(string message, Text tex)
{
int totalLength = 0;
Font myFont = tex.font; //chatText is my Text component
myFont.RequestCharactersInTexture(message, tex.fontSize, tex.fontStyle);
CharacterInfo characterInfo = new CharacterInfo();
char[] arr = message.ToCharArray();
foreach (char c in arr)
{
myFont.GetCharacterInfo(c, out characterInfo, tex.fontSize);
totalLength += characterInfo.advance;
}
return totalLength;
}
}