UICustomTextGradient.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. [AddComponentMenu("UI/Effects/TextGradient")]
  7. [RequireComponent(typeof(Text))]
  8. public class UICustomTextGradient : BaseMeshEffect
  9. {
  10. public Color32 topColor = Color.white;
  11. public Color32 bottomColor = Color.black;
  12. [RangeAttribute(0, 1)]
  13. public float center = 0.5f;
  14. public override void ModifyMesh(VertexHelper vh)
  15. {
  16. if (!IsActive())
  17. {
  18. return;
  19. }
  20. var count = vh.currentVertCount;
  21. if (count == 0)
  22. return;
  23. var vertexs = new List<UIVertex>();
  24. for (var i = 0; i < count; i++)
  25. {
  26. var vertex = new UIVertex();
  27. vh.PopulateUIVertex(ref vertex, i);
  28. vertexs.Add(vertex);
  29. }
  30. var topY = vertexs[0].position.y;
  31. var bottomY = vertexs[0].position.y;
  32. for (var i = 1; i < count; i++)
  33. {
  34. var y = vertexs[i].position.y;
  35. if (y > topY)
  36. {
  37. topY = y;
  38. }
  39. else if (y < bottomY)
  40. {
  41. bottomY = y;
  42. }
  43. }
  44. var height = topY - bottomY;
  45. for (var i = 0; i < count; i++)
  46. {
  47. var vertex = vertexs[i];
  48. //使用处理过后的颜色
  49. // var color = Color32.Lerp(bottomColor, topColor, (vertex.position.y - bottomY) / height);
  50. var color = CenterColor(bottomColor, topColor, (vertex.position.y - bottomY) / height);
  51. vertex.color = color;
  52. vh.SetUIVertex(vertex, i);
  53. }
  54. }
  55. //加了一个对颜色处理的函数,主要调整中心的位置
  56. private Color32 CenterColor(Color32 bc, Color32 tc, float time)
  57. {
  58. if (center == 0)
  59. {
  60. return bc;
  61. }
  62. else if (center == 1)
  63. {
  64. return tc;
  65. }
  66. else
  67. {
  68. var centerColor = Color32.Lerp(bottomColor, topColor, 0.5f);
  69. var resultColor = tc;
  70. if (time < center)
  71. {
  72. resultColor = Color32.Lerp(bottomColor, centerColor, time / center);
  73. }
  74. else
  75. {
  76. resultColor = Color32.Lerp(centerColor, topColor, (time - center) / (1 - center));
  77. }
  78. return resultColor;
  79. }
  80. }
  81. }