Gradient.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using UnityEngine.UI;
  4. [AddComponentMenu("UI/Effects/Gradient")]
  5. public class Gradient : BaseMeshEffect
  6. {
  7. public enum Type
  8. {
  9. Vertical,
  10. Horizontal
  11. }
  12. [SerializeField]
  13. public Type GradientType = Type.Vertical;
  14. [SerializeField]
  15. [Range(-1.5f, 1.5f)]
  16. public float Offset = 0f;
  17. [SerializeField]
  18. public Color32 StartColor = Color.white;
  19. [SerializeField]
  20. public Color32 EndColor = Color.black;
  21. public override void ModifyMesh(VertexHelper helper)
  22. {
  23. if (!IsActive() || helper.currentVertCount == 0)
  24. return;
  25. List<UIVertex> _vertexList = new List<UIVertex>();
  26. helper.GetUIVertexStream(_vertexList);
  27. int nCount = _vertexList.Count;
  28. switch (GradientType)
  29. {
  30. case Type.Vertical:
  31. {
  32. float fBottomY = _vertexList[0].position.y;
  33. float fTopY = _vertexList[0].position.y;
  34. float fYPos = 0f;
  35. for (int i = nCount - 1; i >= 1; --i)
  36. {
  37. fYPos = _vertexList[i].position.y;
  38. if (fYPos > fTopY)
  39. fTopY = fYPos;
  40. else if (fYPos < fBottomY)
  41. fBottomY = fYPos;
  42. }
  43. float fUIElementHeight = 1f / (fTopY - fBottomY);
  44. UIVertex v = new UIVertex();
  45. for (int i = 0; i < helper.currentVertCount; i++)
  46. {
  47. helper.PopulateUIVertex(ref v, i);
  48. v.color = Color32.Lerp(EndColor, StartColor, (v.position.y - fBottomY) * fUIElementHeight - Offset);
  49. helper.SetUIVertex(v, i);
  50. }
  51. }
  52. break;
  53. case Type.Horizontal:
  54. {
  55. float fLeftX = _vertexList[0].position.x;
  56. float fRightX = _vertexList[0].position.x;
  57. float fXPos = 0f;
  58. for (int i = nCount - 1; i >= 1; --i)
  59. {
  60. fXPos = _vertexList[i].position.x;
  61. if (fXPos > fRightX)
  62. fRightX = fXPos;
  63. else if (fXPos < fLeftX)
  64. fLeftX = fXPos;
  65. }
  66. float fUIElementWidth = 1f / (fRightX - fLeftX);
  67. UIVertex v = new UIVertex();
  68. for (int i = 0; i < helper.currentVertCount; i++)
  69. {
  70. helper.PopulateUIVertex(ref v, i);
  71. v.color = Color32.Lerp(EndColor, StartColor, (v.position.x - fLeftX) * fUIElementWidth - Offset);
  72. helper.SetUIVertex(v, i);
  73. }
  74. }
  75. break;
  76. default:
  77. break;
  78. }
  79. }
  80. }