每个字符的显示由两个三角形网格组成,一共六个顶点构成一个字符
0-左上
1-右上
2-右下
3-右下
4-左下
5-左上
UI有四个点,顶点有六个点,做好对应关系
效果如下:
detailText.GetOrAddComponent<TextSpacing>();
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
internal class Line
{
//每行开始顶点索引
private int startVertexIndex;
public int StartVertexIndex
{
get
{
return startVertexIndex;
}
}
//每行结束顶点索引
private int endVertexIndex;
public int EndVertexIndex
{
get
{
return endVertexIndex;
}
}
//每行顶点总量
private int countVertexIndex;
public int CountVertexIndex
{
get
{
return countVertexIndex;
}
}
public Line(int startVertexIndex)
{
this.startVertexIndex = startVertexIndex;
}
public void SetLineEndVertexIndex(int endVertexIndex)
{
this.endVertexIndex = endVertexIndex;
this.countVertexIndex = endVertexIndex-startVertexIndex+1;
}
}
public class TextSpacing : BaseMeshEffect
{
public float spacing = 0;
public override void ModifyMesh(VertexHelper vh)
{
Text text = GetComponent<Text>();
if(text == null || text.text == null){
return;
}
//有换行符的情况
string[] lineTexts = text.text.Split('\n');
int start = 0;
List<int> lineStartIndex = new List<int>();
for(int k = 0 ; k < lineTexts.Length ; k ++){
if(k != 0){
start = start + (lineTexts[k].Length+1)*6;
}
lineStartIndex.Add(start);
}
List<Line> line = new List<Line>();
List<float> lastXList = new List<float>();
List<UIVertex> vertexs = new List<UIVertex>();
vh.GetUIVertexStream(vertexs);
int countVertexIndex = vertexs.Count;
for (int i = 0; i < vertexs.Count; i++)
{
if(i == 0){
line.Add(new Line(0));
}else if(i == vertexs.Count-1){
line[line.Count-1].SetLineEndVertexIndex(i);
lastXList.Add(vertexs[i-2].position.x);
}else{
if(i % 6 == 0){
if(vertexs[i].position.x < vertexs[i-6].position.x){
line[line.Count-1].SetLineEndVertexIndex(i-1);
line.Add(new Line(i));
lastXList.Add(vertexs[i-3].position.x);
}
}
}
}
// DDebug.ZMLog("=====line.Count======"+line.Count);
// for (int i = 0 ; i < line.Count; i++){
// DDebug.ZMLog("====line======="+line[i].StartVertexIndex+"======="+line[i].EndVertexIndex);
// }
// for (int i = 0 ; i < lastXList.Count; i++){
// DDebug.ZMLog("====lastXList======="+lastXList[i]);
// }
int langIndex = GetLongIndex(lastXList);
for (int i = 0; i < line.Count-1; i++)
{
if(langIndex == i){
continue;
}
if(lineStartIndex.Contains(line[i].EndVertexIndex +1)){
continue;
}
spacing = (lastXList[langIndex]-lastXList[i])/(line[i].CountVertexIndex/6);
for (int k = line[i].StartVertexIndex; k <= line[i].EndVertexIndex; k++)
{
UIVertex vertex = vertexs[k];
vertex.position += new Vector3(spacing * ((k-line[i].StartVertexIndex) / 6), 0, 0);
vertexs[k] = vertex;
if (k % 6 <= 2)
{
vh.SetUIVertex(vertex, (k / 6) * 4 + k % 6);
}
if (k % 6 == 4)
{
vh.SetUIVertex(vertex, (k / 6) * 4 + k % 6 - 1);
}
}
}
}
private int GetLongIndex(List<float> list)
{
int index = 0;
for(int i = 1; i < list.Count ; i ++){
if(list[i] > list[index]){
index = i;
}
}
return index;
}
}