在开发过程中,会遇到在文字中间替换、添加一些空间的需求,本篇文章就为大家分享一下如何计算Text控件中字符位置。
首先介绍一下计算方法和思路。
如上图所示,字符都是通过三角面形式渲染出来的,每个字符是由两个三角面组成。要想计算单个字符的位置,就是计算字符所在框体的四个顶点。
通过UnityEngine下的TextGenerator类可以计算指定字符的位置信息
如图四个点就是通过TextGenerator类计算的一个字符的四个顶点位置,从左上角开始,顺时针排序。
通过四个顶点计算出中心点A,可看作为RectTransform中的轴点,如有不同需求,可按照不同算法算出轴点的位置。
下面附上代码
/// <summary>
/// 计算字符坐标
/// </summary>
/// <param name="canvas"> Text所在的Canvas </param>
/// <param name="text"> 要计算字符坐在的Text </param>
/// <param name="charIndex"> 要计算字符在字符串的下标 </param>
void CalculateCharPos(Canvas targetCanvas, Text targetText, int targetCharIndex)
{
string calculateStr = targetText.text;
TextGenerator textGen = new TextGenerator(calculateStr.Length);
Vector2 extents = targetText.GetComponent<RectTransform>().rect.size;
textGen.Populate(calculateStr, targetText.GetGenerationSettings(extents));
int newLine = calculateStr.Substring(0, targetCharIndex).Split('\n').Length - 1;
int whiteSpace = calculateStr.Substring(0, targetCharIndex).Split(' ').Length - 1;
int indexOfTextQuad = targetCharIndex * 4;
Vector3 charPos1 = textGen.verts[indexOfTextQuad].position / targetCanvas.scaleFactor;
Vector3 charPos2 = textGen.verts[indexOfTextQuad + 1].position / targetCanvas.scaleFactor;
Vector3 charPos3 = textGen.verts[indexOfTextQuad + 2].position / targetCanvas.scaleFactor;
Vector3 charPos4 = textGen.verts[indexOfTextQuad + 3].position / targetCanvas.scaleFactor;
point1.localPosition = charPos1;
point2.localPosition = charPos2;
point3.localPosition = charPos3;
point4.localPosition = charPos4;
Debug.LogFormat("point1 : {0}", charPos1);
Debug.LogFormat("point2 : {0}", charPos2);
Debug.LogFormat("point3 : {0}", charPos3);
Debug.LogFormat("point4 : {0}", charPos4);
if (indexOfTextQuad < textGen.vertexCount)
{
Vector3 avgPos = (textGen.verts[indexOfTextQuad].position +
textGen.verts[indexOfTextQuad + 1].position +
textGen.verts[indexOfTextQuad + 2].position +
textGen.verts[indexOfTextQuad + 3].position) / 4f;
avgPoint.localPosition = avgPos;
}
}
注意:textGen.verts中存的是Text组件中所有每个字符的四个顶点信息
例如:第一个字符,顶点:0,1,2,3
第二个字符,顶点:4,5,6,7
第三个字符,顶点:8,9,10,11
…
所以计算第x个字符的顶点位置,需要找到textGen.verts中下标为4x,4x+1,4x+2,4x+3的四个顶点。
以上代码仅供参考
其他
更多Blog请见:https://yiyuan1130.github.io/
Github地址:https://github.com/yiyuan1130