HorizontalSegmentsPrimitive.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // UnityEngine.UI was moved to a package in 2019.2.0
  2. // Unfortunately no way to test for this across all Unity versions yet
  3. // You can set up the asmdef to reference the new package, but the package doesn't
  4. // existing in Unity 2017 etc, and it throws an error due to missing reference
  5. #define AVPRO_PACKAGE_UNITYUI
  6. #if (UNITY_2019_2_OR_NEWER && AVPRO_PACKAGE_UNITYUI) || (!UNITY_2019_2_OR_NEWER)
  7. using UnityEngine;
  8. using UnityEngine.UI;
  9. namespace RenderHeads.Media.AVProVideo.Demos.UI
  10. {
  11. /// Fill a rectangle region with horizontal segments along it
  12. [ExecuteInEditMode]
  13. public class HorizontalSegmentsPrimitive : Graphic
  14. {
  15. private float[] _segments = { 0f, 0f };
  16. public float[] Segments { get { return _segments; } set { SetSegments(value); } }
  17. private void SetSegments(float[] segments)
  18. {
  19. if (segments != null && segments.Length > 1)
  20. {
  21. _segments = segments;
  22. }
  23. else
  24. {
  25. _segments = new float[] { 0f, 0f };
  26. }
  27. // TODO: detect whether a change actually occured before setting to dirty
  28. SetVerticesDirty();
  29. }
  30. protected override void OnPopulateMesh(VertexHelper vh)
  31. {
  32. Vector2 corner1 = Vector2.zero;
  33. Vector2 corner2 = Vector2.zero;
  34. corner1.x = 0f;
  35. corner1.y = 0f;
  36. corner2.x = 1f;
  37. corner2.y = 1f;
  38. corner1.x -= rectTransform.pivot.x;
  39. corner1.y -= rectTransform.pivot.y;
  40. corner2.x -= rectTransform.pivot.x;
  41. corner2.y -= rectTransform.pivot.y;
  42. corner1.x *= rectTransform.rect.width;
  43. corner1.y *= rectTransform.rect.height;
  44. corner2.x *= rectTransform.rect.width;
  45. corner2.y *= rectTransform.rect.height;
  46. vh.Clear();
  47. int numQuads = _segments.Length / 2;
  48. UIVertex vert = UIVertex.simpleVert;
  49. int vi = 0;
  50. for (int i = 0; i < numQuads; i++)
  51. {
  52. float x1 = _segments[i * 2 + 0] * (corner2.x - corner1.x) + corner1.x;
  53. float x2 = _segments[i * 2 + 1] * (corner2.x - corner1.x) + corner1.x;
  54. vert.position = new Vector2(x1, corner1.y);
  55. vert.color = color;
  56. vh.AddVert(vert);
  57. vert.position = new Vector2(x1, corner2.y);
  58. vert.color = color;
  59. vh.AddVert(vert);
  60. vert.position = new Vector2(x2, corner2.y);
  61. vert.color = color;
  62. vh.AddVert(vert);
  63. vert.position = new Vector2(x2, corner1.y);
  64. vert.color = color;
  65. vh.AddVert(vert);
  66. vh.AddTriangle(0 + vi, 1 + vi, 2 + vi);
  67. vh.AddTriangle(2 + vi, 3 + vi, 0 + vi);
  68. vi += 4;
  69. }
  70. }
  71. }
  72. }
  73. #endif