Unity UI Text 计算字符距离

在开发过程中,会遇到在文字中间替换、添加一些空间的需求,本篇文章就为大家分享一下如何计算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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值