TextSpacing.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections.Generic;
  4. public class Line
  5. {
  6. private int _startVertexIndex = 0;
  7. /// <summary>
  8. /// 起点索引
  9. /// </summary>
  10. public int StartVertexIndex
  11. {
  12. get
  13. {
  14. return _startVertexIndex;
  15. }
  16. }
  17. private int _endVertexIndex = 0;
  18. /// <summary>
  19. /// 终点索引
  20. /// </summary>
  21. public int EndVertexIndex
  22. {
  23. get
  24. {
  25. return _endVertexIndex;
  26. }
  27. }
  28. private int _vertexCount = 0;
  29. /// <summary>
  30. /// 该行占的点数目
  31. /// </summary>
  32. public int VertexCount
  33. {
  34. get
  35. {
  36. return _vertexCount;
  37. }
  38. }
  39. public Line(int startVertexIndex, int length)
  40. {
  41. _startVertexIndex = startVertexIndex;
  42. _endVertexIndex = length * 6 - 1 + startVertexIndex;
  43. _vertexCount = length * 6;
  44. }
  45. }
  46. [AddComponentMenu("UI/Effects/TextSpacing")]
  47. public class TextSpacing : BaseMeshEffect
  48. {
  49. public float _textSpacing = 1f;
  50. public override void ModifyMesh(VertexHelper vh)
  51. {
  52. if (!IsActive() || vh.currentVertCount == 0)
  53. {
  54. return;
  55. }
  56. Text text = GetComponent<Text>();
  57. if (text == null)
  58. {
  59. Debug.LogError("Missing Text component");
  60. return;
  61. }
  62. List<UIVertex> vertexs = new List<UIVertex>();
  63. vh.GetUIVertexStream(vertexs);
  64. int indexCount = vh.currentIndexCount;
  65. string[] lineTexts = text.text.Split('\n');
  66. Line[] lines = new Line[lineTexts.Length];
  67. //根据lines数组中各个元素的长度计算每一行中第一个点的索引,每个字、字母、空母均占6个点
  68. for (int i = 0; i < lines.Length; i++)
  69. {
  70. //除最后一行外,vertexs对于前面几行都有回车符占了6个点
  71. if (i == 0)
  72. {
  73. lines[i] = new Line(0, lineTexts[i].Length + 1);
  74. }
  75. else if (i > 0 && i < lines.Length - 1)
  76. {
  77. lines[i] = new Line(lines[i - 1].EndVertexIndex + 1, lineTexts[i].Length + 1);
  78. }
  79. else
  80. {
  81. lines[i] = new Line(lines[i - 1].EndVertexIndex + 1, lineTexts[i].Length);
  82. }
  83. }
  84. UIVertex vt;
  85. for (int i = 0; i < lines.Length; i++)
  86. {
  87. for (int j = lines[i].StartVertexIndex + 6; j <= lines[i].EndVertexIndex; j++)
  88. {
  89. if (j < 0 || j >= vertexs.Count)
  90. {
  91. continue;
  92. }
  93. vt = vertexs[j];
  94. vt.position += new Vector3(_textSpacing * ((j - lines[i].StartVertexIndex) / 6), 0, 0);
  95. vertexs[j] = vt;
  96. //以下注意点与索引的对应关系
  97. if (j % 6 <= 2)
  98. {
  99. vh.SetUIVertex(vt, (j / 6) * 4 + j % 6);
  100. }
  101. if (j % 6 == 4)
  102. {
  103. vh.SetUIVertex(vt, (j / 6) * 4 + j % 6 - 1);
  104. }
  105. }
  106. }
  107. }
  108. }