竖排文字网络上主要的实现方式有两种
第一种是对数据进行处理,横转竖排,空格占位。
第二种是重新绘制mesh,重写ModifyMesh方法。
为了一步到位,选择了第二种,但是之前网上的方法,在2019版本上用是报错的,不能支持换行等。这是因为新版unity对text的顶点数管理发生了升级。没办法,只好自己搞一个。顺便支持一下简单的html格式,比如变换颜色,换行,换行变颜色等一些需求,毕竟项目中都要用。
下面这个是老版的报错信息,
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
顶点数对不上啦。
不多说了,贴一些代码
public override void ModifyMesh(VertexHelper helper)
{
if (!IsActive())
return;
List<UIVertex> verts = new List<UIVertex>();
helper.GetUIVertexStream(verts);
Text text = GetComponent<Text>();
string realText = GetStringNoHtml(text.text);
TextGenerator tg = text.cachedTextGenerator;
lineSpacing = text.fontSize * text.lineSpacing;
textSpacing = text.fontSize * spacing;
xOffset = text.rectTransform.sizeDelta.x / 2 - text.fontSize / 2;
yOffset = text.rectTransform.sizeDelta.y / 2 - text.fontSize / 2;
List<UILineInfo> lines = new List<UILineInfo>();
tg.GetLines(lines);
int needDelNum = 0;
for (int i = 0; i < lines.Count; i++)
{
UILineInfo line = lines[i];
int step = i;
int current = 0;
int endCharIdx = (i + 1 == lines.Count) ? tg.characterCountVisible : lines[i + 1].startCharIdx;
for (int j = line.startCharIdx; j < endCharIdx; j++)
{
bool isMatch = Regex.IsMatch(text.text[j].ToString(), strRegex);
bool isShow = (realText.Length > j - needDelNum) &&
text.text[j].ToString() == realText[j - needDelNum].ToString();
if (!isMatch && isShow)
{
modifyText(helper, j - needDelNum, current++, step);
}
else
{
needDelNum++;
if (isMatch)
{
break;
}
}
}
}
}
效果图如下:
整个可运行的工程,请移步下面的链接。我打成了一个包直接传了。