Unity3d Text 文字排版问题

1.中英混排空格换行问题

//使用不间断的空格替换普通空格
//有三种空格格式
//1.不间断空格  \u00A0
//2.半角空格    \u0020
//3.全角空格    \u3000
var text = text.Replace(" ", "\u00A0");

2.行首添加两个空格

//开头添加俩空格
var text = "\u3000\u3000" + text.Replace(" ", "\u00A0");
//如果有换行符,换行符后面加俩空格
text = text.Replace("\n", "\n\u3000\u3000");

3.标点在行首,写一个新的Text类重载SetVerticesDirty方法

public class CustomText : Text
{
    private readonly string mArkList = @"(\!|\?|\,|\。|\《|\》|\)|\:|\“|\‘|\、|\;|\+|\-)";

    public override void SetVerticesDirty()
    {
        var settings = GetGenerationSettings(rectTransform.rect.size);
        cachedTextGenerator.Populate(text, settings);

        StringBuilder stringBuilder = new StringBuilder(text);
        IList lineList = cachedTextGenerator.lines;
        int changeIndex = -1;
        for (int i = 1; i < lineList.Count; i++)
        {
            bool isMark = Regex.IsMatch(text[lineList[i].startCharIdx].ToString(), mArkList);

            if (isMark)
            {
                bool b = Regex.IsMatch(text[lineList[i].startCharIdx].ToString(), mArkList);
                if (b)
                {
                    changeIndex = lineList[i].startCharIdx - 1;
                    break;
                }
            }
        }

        if (changeIndex >= 0)
        {
            stringBuilder.Insert(changeIndex, '\n');
            text = stringBuilder.ToString();
        }

        base.SetVerticesDirty();
    }
}

 

你可能感兴趣的:(Unity3d,UI)