因为项目需要UGUI的Text组件文字间距动态改变,因此想从网上找一下教程,发现很多都要么不支持富文本,要么换行有问题,于是随便找一份后,自己修改了其中间距的算法,还有实现了支持富文本的功能。
支持富文本的原理
- 看到网上有个实现是遍历每行字符串,然后计算Spacing,但是这样会把富文本的字符也计算进去,导致最终效果不理想。于是我改成遍历顶点,因为那些富文本字符没有实际绘制出来,所以不会出现在顶点数组中。不过需要判断每一行有多少个顶点,目前是通过遍历顶点的位置高度,如果超过fontSize(lineSpacing也有影响,目前还没考虑进去),则认为不在同一行。
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextSpacing : BaseMeshEffect
{
public enum HorizontalAligmentType
{
Left,
Center,
Right
}
public class Line
{
// 起点索引
public int StartVertexIndex {
get {
return _startVertexIndex; } }
private int _startVertexIndex = 0;
// 终点索引
public int EndVertexIndex {
get {
return _endVertexIndex; } }
private int _endVertexIndex = 0;
public Line(int startVertexIndex, int length)
{
_startVertexIndex = startVertexIndex;
_endVertexIndex = length * vertexPreChar - 1 + startVertexIndex;
}
}
public float Spacing = 1f;
//每个字需要6个顶点绘制,即2个三角形
private const int vertexPreChar = 6;
public override void ModifyMesh(VertexHelper vh)
{
if (!IsActive() || vh.currentVertCount == 0)