【Unity-UGUI-Text】中文里带半角空格导致的Text换行问题

版权声明: https://blog.csdn.net/IT_yanghui/article/details/82591701

我们平时所使用的空格(即键盘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

猜你喜欢

转载自blog.csdn.net/IT_yanghui/article/details/82591701