更新:还是使用Unity的TexMesh Pro 比较好,运行快,自动排除首行出现标点的可能。富文本还好用。
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, '\n');
this.text = textStr.ToString();
}
base.SetVerticesDirty();
}
如果文字过多,这个代码执行一次后,会影响其他文字,下面的还是可能会出现标点符号出现在首位。。