UGUI之修改Text字間距
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.Collections.Generic;
public class Line
{
private int _startVertexIndex = 0;
/// <summary>
/// 起點索引
/// </summary>
public int StartVertexIndex
{
get
{
return _startVertexIndex;
}
}
private int _endVertexIndex = 0;
/// <summary>
/// 終點索引
/// </summary>
public int EndVertexIndex
{
get
{
return _endVertexIndex;
}
}
private int _vertexCount = 0;
/// <summary>
/// 該行佔的點數目
/// </summary>
public int VertexCount
{
get
{
return _vertexCount;
}
}
public Line(int startVertexIndex,int length)
{
_startVertexIndex = startVertexIndex;
_endVertexIndex = length * 6 - 1 + startVertexIndex;
_vertexCount = length * 6;
}
}
[AddComponentMenu("UI/Effects/TextSpacing")]
public class TextSpacing : BaseMeshEffect
{
public float _textSpacing = 1f;
public override void ModifyMesh(VertexHelper vh)
{
if (!IsActive() || vh.currentVertCount == 0)
{
return;
}
Text text = GetComponent<Text>();
if (text == null)
{
Debug.LogError("Missing Text component");
return;
}
List<UIVertex> vertexs = new List<UIVertex>();
vh.GetUIVertexStream(vertexs);
int indexCount = vh.currentIndexCount;
string[] lineTexts = text.text.Split('\n');
Line[] lines = new Line[lineTexts.Length];
//根據lines陣列中各個元素的長度計算每一行中第一個點的索引,每個字、字母、空母均佔6個點
for (int i = 0; i < lines.Length; i++)
{
//除最後一行外,vertexs對於前面幾行都有回車符佔了6個點
if (i == 0)
{
lines[i] = new Line(0, lineTexts[i].Length + 1);
}
else if(i > 0 && i < lines.Length - 1)
{
lines[i] = new Line(lines[i - 1].EndVertexIndex + 1, lineTexts[i].Length + 1);
}
else
{
lines[i] = new Line(lines[i - 1].EndVertexIndex + 1, lineTexts[i].Length);
}
}
UIVertex vt;
for (int i = 0; i < lines.Length; i++)
{
for (int j = lines[i].StartVertexIndex + 6; j <= lines[i].EndVertexIndex; j++)
{
if (j < 0 || j >= vertexs.Count)
{
continue;
}
vt = vertexs[j];
vt.position += new Vector3(_textSpacing * ((j - lines[i].StartVertexIndex) / 6), 0, 0);
vertexs[j] = vt;
//以下注意點與索引的對應關係
if (j % 6 <= 2)
{
vh.SetUIVertex(vt, (j / 6) * 4 + j % 6);
}
if (j % 6 == 4)
{
vh.SetUIVertex(vt, (j / 6) * 4 + j % 6 - 1);
}
}
}
}
}
---------------------
作者:qq_26999509
來源:CSDN
原文:https://blog.csdn.net/qq_26999509/article/details/51902551
版權宣告:本文為博主原創文章,轉載請附上博文連結!