Gradient1.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. *FileName: Gradient.cs
  3. *Author: M
  4. *Date: 2022/02/23 13:51:26
  5. *UnityVersion: 2020.3.0f1c1
  6. *Description: ͼƬ½¥±äЧ¹û
  7. */
  8. using UnityEngine;
  9. using UnityEngine.UI;
  10. [AddComponentMenu("UI/Effects/Gradient")]
  11. public class Gradient1 : BaseMeshEffect
  12. {
  13. public Color Color1 = Color.white;
  14. public Color Color2 = Color.white;
  15. [Range(-180f, 180f)] public float Angle = -90.0f;
  16. public override void ModifyMesh(VertexHelper vh)
  17. {
  18. if (enabled)
  19. {
  20. var rect = graphic.rectTransform.rect;
  21. var dir = RotationDir(Angle);
  22. var localPositionMatrix = LocalPositionMatrix(rect, dir);
  23. var vertex = default(UIVertex);
  24. for (var i = 0; i < vh.currentVertCount; i++)
  25. {
  26. vh.PopulateUIVertex(ref vertex, i);
  27. var localPosition = localPositionMatrix * vertex.position;
  28. vertex.color *= Color.Lerp(Color2, Color1, localPosition.y);
  29. vh.SetUIVertex(vertex, i);
  30. }
  31. }
  32. }
  33. public struct Matrix2x3
  34. {
  35. public float m00, m01, m02, m10, m11, m12;
  36. public Matrix2x3(float m00, float m01, float m02, float m10, float m11, float m12)
  37. {
  38. this.m00 = m00;
  39. this.m01 = m01;
  40. this.m02 = m02;
  41. this.m10 = m10;
  42. this.m11 = m11;
  43. this.m12 = m12;
  44. }
  45. public static Vector2 operator *(Matrix2x3 m, Vector2 v)
  46. {
  47. float x = (m.m00 * v.x) - (m.m01 * v.y) + m.m02;
  48. float y = (m.m10 * v.x) + (m.m11 * v.y) + m.m12;
  49. return new Vector2(x, y);
  50. }
  51. }
  52. private Matrix2x3 LocalPositionMatrix(Rect rect, Vector2 dir)
  53. {
  54. float cos = dir.x;
  55. float sin = dir.y;
  56. Vector2 rectMin = rect.min;
  57. Vector2 rectSize = rect.size;
  58. float c = 0.5f;
  59. float ax = rectMin.x / rectSize.x + c;
  60. float ay = rectMin.y / rectSize.y + c;
  61. float m00 = cos / rectSize.x;
  62. float m01 = sin / rectSize.y;
  63. float m02 = -(ax * cos - ay * sin - c);
  64. float m10 = sin / rectSize.x;
  65. float m11 = cos / rectSize.y;
  66. float m12 = -(ax * sin + ay * cos - c);
  67. return new Matrix2x3(m00, m01, m02, m10, m11, m12);
  68. }
  69. private Vector2 RotationDir(float angle)
  70. {
  71. float angleRad = angle * Mathf.Deg2Rad;
  72. float cos = Mathf.Cos(angleRad);
  73. float sin = Mathf.Sin(angleRad);
  74. return new Vector2(cos, sin);
  75. }
  76. }