o0UIRawImageTester.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class o0UIRawImageTester : MonoBehaviour
  6. {
  7. static HashSet<o0UIRawImageTester> Testers = new HashSet<o0UIRawImageTester>();
  8. public static void UpdateAllOffset()
  9. {
  10. foreach (var i in Testers)
  11. i.UpdateOffset();
  12. }
  13. RawImage Image;
  14. Texture2D Texture;
  15. int Offset = 0;
  16. // Start is called before the first frame update
  17. void Awake()
  18. {
  19. Testers.Add(this);
  20. Image = GetComponent<RawImage>();
  21. var rect = GetComponent<RectTransform>().rect;
  22. Texture = new Texture2D((int)rect.width, (int)rect.height);
  23. Image.texture = Texture;
  24. ColorBuffer[new Color(1, 0, 0)] = new Color[] { new Color(1, 0, 0) , new Color(1, 0, 0) };
  25. //Debug.Log(ColorBuffer[new Color(1, 0, 0)].Length);
  26. }
  27. // Update is called once per frame
  28. void Update()
  29. {
  30. }
  31. static Dictionary<Color, Color[]> ColorBuffer = new Dictionary<Color, Color[]>();
  32. static Color[] GetColorArray(Color color, int length)
  33. {
  34. if (ColorBuffer.ContainsKey(color))
  35. {
  36. if (ColorBuffer[color].Length >= length)
  37. return ColorBuffer[color];
  38. else
  39. ColorBuffer.Remove(color);
  40. }
  41. var c = new Color[length];
  42. for (var i = 0; i < c.Length; ++i)
  43. c[i] = color;
  44. ColorBuffer.Add(color, c);
  45. return c;
  46. }
  47. public void DrawPoint(int height, Color color)
  48. {
  49. if (height > Texture.height)
  50. height = Texture.height;
  51. else if (height < 0)
  52. height = 0;
  53. Texture.SetPixel(Offset, height, color);
  54. Texture.Apply();
  55. }
  56. public void DrawLine(int height, Color color)
  57. {
  58. if (height > Texture.height)
  59. height = Texture.height;
  60. else if (height < 0)
  61. height = 0;
  62. Texture.SetPixels(Offset, 0, 1, height, GetColorArray(color, height));
  63. Texture.Apply();
  64. }
  65. public void DrawPoint(float height, Color color)
  66. {
  67. DrawPoint((int)(height * Texture.height), color);
  68. }
  69. public void DrawLine(float height, Color color)
  70. {
  71. DrawLine((int)(height * Texture.height), color);
  72. }
  73. public virtual void UpdateOffset()
  74. {
  75. ++Offset;
  76. if (Offset >= Texture.width)
  77. Offset = 0;
  78. var rect = Image.uvRect;
  79. rect.x = (float)(Offset+1) / Texture.width;
  80. Image.uvRect = rect;
  81. DrawLine(1f,new Color(1,1,1,0.5f));
  82. }
  83. }