【Unity】Text文本符号处理

Unity的Text组件的文字不会像word之类的自动处理首字符是符号的段落文字,会出现下面的,一行文字第一个字符是符号,这样不美观不合适。

 

 

Text赋值之后,使用IList<UILineInfo>取出文字的行内容,使用正则表达式,比较第一个字符是否是符号,如果是符号,在符号前一个字符之前插入回车,提前换行,再储存文本内容循环检测。

 

使用时因为需要在Text赋值之后才能获取每行信息,所以会滞后一帧刷新重新布局的内容

 

代码如下:

复制代码
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;

public class TextSymbolProcessing : MonoBehaviour
{
    /// <summary>
    /// 用于匹配标点符号
    /// </summary>
    //private readonly string strRegex = @"(\!|\?|\,|\。|\《|\》|\(|\)|\(|\)|\:|\“|\‘|\、|\;|\+|\-|\·|\#|\¥|\;|\”|\【|\】|\——)";

    /// <summary>
    /// 首行标点符合
    /// </summary>
    private readonly string strRegex1 = @"(\!|\?|\,|\。|\《|\》|\)|\(|\)|\:|\“|\‘|\、|\;|\+|\-|\·|\#|\¥|\;|\”|\【|\】|\——|\<|\>)";

    /// <summary>
    /// 用于存储text组件中的内容
    /// </summary>
    private StringBuilder textSB = null;

    /// <summary>
    /// 用于存储text生成器中的内容
    /// </summary>
    private IList<UILineInfo> textLineInfo;

    //文本符号处理
    public IEnumerator SymbolProcess(Text textComponent, string textStr)
    {
        textComponent.text = textStr;
        while (true)
        {
            yield return 0;
            textLineInfo = textComponent.cachedTextGenerator.lines;
            textSB = new StringBuilder(textComponent.text);

            for (int i = 1; i < textLineInfo.Count; i++)
            {
                bool isMark = Regex.IsMatch(textComponent.text[textLineInfo[i].startCharIdx].ToString(), strRegex1);

                if (isMark)
                {
                    if (textComponent.text[textLineInfo[i].startCharIdx - 1].ToString() == "\n")
                    {
                        textSB.Remove(textLineInfo[i].startCharIdx - 1, 1);
                        textSB.Insert(textLineInfo[i].startCharIdx - 2, '\n');
                    }
                    else
                    {
                        textSB.Insert(textLineInfo[i].startCharIdx - 1, '\n');
                    }
                    StartCoroutine(SymbolProcess(textComponent, textSB.ToString()));
                    break;
                }
            }
            break;
        }
    }
}
复制代码

 

posted @   weigang  阅读(1206)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示