unity之中Text控件行首不出現標點符號

看了好多資料,沒一個正常的,自己寫了一個,在大多數情況下可以看,比如連着好幾個標點符號出現在行首,但是標點符號出現在行尾的情況還不能處理,僅供參考

 

using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Text))]
public class TextFit : Text
{
    /// <summary>
    /// 用於匹配標點符號(正則表達式)
    /// </summary>
    private readonly string strRegex = @"(\!|\?|\,|\。|\《|\》|\(|\)|\(|\)|\:|\“|\‘|\、|\;|\+|\-|\·|\#|\¥|\;|\”|\【|\】|\——|\/)";


    /// <summary>
    /// 用於存儲text組件中的內容
    /// </summary>
    private System.Text.StringBuilder MExplainText = null;

    /// <summary>
    /// 用於存儲text生成器中的內容
    /// </summary>
    private IList<UILineInfo> MExpalinTextLine;

    protected override void OnPopulateMesh(VertexHelper toFill)
    {
        base.OnPopulateMesh(toFill);
        StartCoroutine(MClearUpExplainMode(this, text));
    }


    IEnumerator MClearUpExplainMode(Text _component, string _text)
    {
        _component.text = _text;

        //如果直接執行下邊方法的話,那麼_component.cachedTextGenerator.lines將會獲取的是之前text中的內容,而不是_text的內容,所以需要等待一下
        yield return new WaitForSeconds(0.001f);
        MExpalinTextLine = _component.cachedTextGenerator.lines;
        MExplainText = new System.Text.StringBuilder(_component.text);
        

        for (int i = 1; i < MExpalinTextLine.Count; i++)
        {
            int CheckId = MExpalinTextLine[i].startCharIdx;
            //首位是否有標點
            while (Regex.IsMatch(_component.text[CheckId].ToString(), strRegex))
            {
                CheckId--;
                if (CheckId == 0 || CheckId - 1 == 0)
                {
                    break;
                }
                //不考慮標點符號前有人爲換行的情況
                if(_component.text[CheckId].ToString() == "\n")
                {
                    MExplainText.Remove(CheckId, 1);
                }
                else
                {
                    MExplainText.Insert(CheckId, '\n');
                }                
            }            
        }


        _component.text = MExplainText.ToString();
    }
}

使用時,去掉Text原本的組件,把這個腳本拖上去代替,就可以了

參考資料:

https://www.cnblogs.com/PandaQ/p/9946430.html

https://blog.csdn.net/dengshunhao/article/details/86659401

https://blog.csdn.net/seek_yang/article/details/113183488

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章