zoukankan      html  css  js  c++  java
  • 【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() == "
    ")
                        {
                            textSB.Remove(textLineInfo[i].startCharIdx - 1, 1);
                            textSB.Insert(textLineInfo[i].startCharIdx - 2, '
    ');
                        }
                        else
                        {
                            textSB.Insert(textLineInfo[i].startCharIdx - 1, '
    ');
                        }
                        StartCoroutine(SymbolProcess(textComponent, textSB.ToString()));
                        break;
                    }
                }
                break;
            }
        }
    }
  • 相关阅读:
    当Django模型迁移时,报No migrations to apply 问题时
    django--各个文件的含义
    django--创建项目
    1013. Battle Over Cities (25)
    1011. World Cup Betting (20)
    1009. Product of Polynomials (25)
    1007. Maximum Subsequence Sum (25)
    1006. Sign In and Sign Out (25)
    1008. Elevator (20)
    1004. Counting Leaves (30)
  • 原文地址:https://www.cnblogs.com/weigangblog/p/14371053.html
Copyright © 2011-2022 走看看