先放其它的参考
https://blog.csdn.net/BDDNH/article/details/100704862
https://blog.csdn.net/ecidevilin/article/details/52577333
https://blog.csdn.net/wayway0554/article/details/80738071
UGUI源代码:
https://bitbucket.org/Unity-Technologies/ui/src/2019.1/
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 有时候,我们要根据文字对Text进行排版,这就要我们知道每个字符的尺寸
/// 比如,tips,要根据文本区域,去缩放底板的尺寸
/// </summary>
/// <summary>
/// 我们可以从 Text 派生,并重写 OnPopulate 方法,生成 Mesh,来渲染文字
/// </summary>
public class MyText : Text
{
protected override void OnPopulateMesh(VertexHelper toFill)
{
base.OnPopulateMesh(toFill);
}
}
// 测试代码
public class GetTextSize : MonoBehaviour
{
public Image img;
public Text txt;
// Start is called before the first frame update
void Start()
{
//GetLines("niha<color=blue>艾利的天镜</color>oa!123avg你好啊!nihaoa!123avg你好啊!nihaoa!123avg你好啊!nihaoa!123avg你好啊!nihaoa!123avg你好啊!");
txt.text = "nihaoa!123avg你好啊!";
RectTransform rt = img.GetComponent<RectTransform>();
float w = GetPreferedWidth(txt.text); // 已经对txt.text赋值的情况下,也可以 w = txt.preferredWidth;
float h = GetPreferedHeight(txt.text); // 已经对txt.text赋值的情况下,也可以 h = txt.preferredHeight;
rt.sizeDelta = new Vector2(w, h);
}
// Update is called once per frame
void Update()
{
}
public float GetPreferedWidth(string str)
{
TextGenerationSettings ts = txt.GetGenerationSettings(Vector2.zero);
txt.cachedTextGeneratorForLayout.GetPreferredWidth(str, ts);
return 0;
}
public float GetPreferedHeight(string str)
{
TextGenerationSettings ts = txt.GetGenerationSettings(Vector2.zero);
txt.cachedTextGeneratorForLayout.GetPreferredHeight(str, ts);
return 0;
}
public void GetLines(string str, List<string> allLns)
{
TextGenerationSettings ts = txt.GetGenerationSettings(Vector2.zero);
if (ts.verticalOverflow == VerticalWrapMode.Overflow)
{
txt.cachedTextGeneratorForLayout.Populate(str, ts);
RectTransform rt = txt.GetComponent<RectTransform>();
UICharInfo[] arrChi = txt.cachedTextGeneratorForLayout.GetCharactersArray();
float lnWidth = 0;
string strLn = "";
for (int i = 0; i < arrChi.Length; ++i)
{
lnWidth += arrChi[i].charWidth;
if (lnWidth > rt.sizeDelta.x)
{
allLns.Add(strLn);
strLn = "";
lnWidth = 0;
}
if (i >= str.Length)
break;
strLn += str[i];
}
if (strLn.Length > 0)
allLns.Add(strLn);
}
else
{
allLns.Add(str);
}
}
}