RectTransformExtensions.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using UnityEngine;
  6. namespace TheraBytes.BetterUi
  7. {
  8. public static class RectTransformExtensions
  9. {
  10. public static Rect ToScreenRect(this RectTransform self, bool startAtBottom = false, Canvas canvas = null,
  11. bool localTransform = false)
  12. {
  13. Vector3[] corners = new Vector3[4];
  14. Vector3[] screenCorners = new Vector3[2];
  15. if (localTransform)
  16. {
  17. self.GetLocalCorners(corners);
  18. }
  19. else
  20. {
  21. self.GetWorldCorners(corners);
  22. }
  23. int idx1 = (startAtBottom) ? 0 : 1;
  24. int idx2 = (startAtBottom) ? 2 : 3;
  25. if (canvas != null && (canvas.renderMode == RenderMode.ScreenSpaceCamera || canvas.renderMode == RenderMode.WorldSpace))
  26. {
  27. screenCorners[0] = RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, corners[idx1]);
  28. screenCorners[1] = RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, corners[idx2]);
  29. }
  30. else
  31. {
  32. screenCorners[0] = RectTransformUtility.WorldToScreenPoint(null, corners[idx1]);
  33. screenCorners[1] = RectTransformUtility.WorldToScreenPoint(null, corners[idx2]);
  34. }
  35. if (!(startAtBottom))
  36. {
  37. screenCorners[0].y = Screen.height - screenCorners[0].y;
  38. screenCorners[1].y = Screen.height - screenCorners[1].y;
  39. }
  40. return new Rect(screenCorners[0], screenCorners[1] - screenCorners[0]);
  41. }
  42. }
  43. }