Unity 行首不出现中文标点
Unity对标点是没有做过处理的 所有现在有一个需求是处理行首不能出现标点
这种情况看着很不美观,修正方法:吧上一行的最后一个字拉下来
如果有多个标点的话,都拉下来
代码
private readonly string markList = "(!|?|,|。|《|》|)|:|“|‘|、|;|+|-)"; StringBuilder textStr; public override void SetVerticesDirty() { var settings = GetGenerationSettings(rectTransform.rect.size); cachedTextGenerator.Populate(this.text, settings); textStr = new StringBuilder(this.text); IList<UILineInfo> lineList = this.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) { changeIndex = lineList[i].startCharIdx - 1; string str = text.Substring(lineList[i - 1].startCharIdx, lineList[i].startCharIdx); MatchCollection richStrMatch = Regex.Matches(str, ".(</color>|<color=#\w{6}>|" + markList + ")+$"); if (richStrMatch.Count > 0) { string richStr = richStrMatch[0].ToString(); int length = richStr.Length; changeIndex = lineList[i].startCharIdx - length; break; } } } if (changeIndex >= 0) { textStr.Insert(changeIndex, ' '); this.text = textStr.ToString(); } base.SetVerticesDirty(); }
原理
Text是继承Graphic的,所以在改变Text.text时,渲染会脏掉,此时重新渲染,在渲染之前进行正则表达式处理文字。
注意:
1.建议在想要处理标签枚举的前面都加上,防止出现出现如+这样的正则表达式关键字导致代码报错。
2.使用StringBuilder,C#中不可修改String。
3.修改文字的textStr用全局变量,防止GC。