1. 程式人生 > >【Unity-UGUI-Text】中文裡帶半形空格導致的Text換行問題

【Unity-UGUI-Text】中文裡帶半形空格導致的Text換行問題

我們平時所使用的空格(即鍵盤Sapce鍵輸出的空格),Unicode編碼為/u0020,是換行空格(Breaking Space),空格前後的內容是允許自動換行的;與之對應的不換行空格(Non-breaking space),Unicode編碼為/u00A0,顯示與換行空格一樣,主要用途用於禁止自動換行,在英文中主要用於避免類似(100 KM)這種文字被錯誤地分詞排版成兩行。可以說,Breaking Space的存在讓西語得以分隔單詞,從而正確地分詞排版,但放在中文裡是多餘的存在,中文沒有單詞概念,不需要做分隔。

那這下問題就好解決了,我們只需在Text元件設定text時,將字串的換行空格統一更換成不換行空格,就能解決換行錯誤問題。新建一個NonBreakingSpaceTextComponent類,做文字替換處理:

/* ==============================================================================
 * 功能描述:將Text元件的space(0x0020)替換為No-break-space(0x00A0),避免中文使用半形空格導致的提前換行問題
 * ==============================================================================*/

using UnityEngine.UI;
using UnityEngine;

[RequireComponent(typeof(Text))]
public class NonBreakingSpaceTextComponent : MonoBehaviour
{
    public static readonly string no_breaking_space = "\u00A0";

    protected Text text;
    // Use this for initialization
    void Awake ()
    {
        text = this.GetComponent<Text>();
        text.RegisterDirtyVerticesCallback(OnTextChange);
    }

    public void OnTextChange()
    {
        if (text.text.Contains(" "))
        {
            text.text = text.text.Replace(" ", no_breaking_space);
        }
    }

}

將NoBreakingSpaceTextComponent掛在Text元件上,每當Text設定text文字,準備重新繪製Text網格時,NoBreakingSpaceTextComponent會檢查並替換text文字裡的換行空格。

此部落格只為知識學習與分享!如有侵權,聯絡刪除。謝謝!

來自部落格園:https://www.cnblogs.com/leoin2012/p/7162099.html