UISafeArea.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. using UnityEngine.UI;
  6. public class UISafeArea : UIControlArea
  7. {
  8. [SerializeField]
  9. private bool m_LeftSafe = false;
  10. [SerializeField]
  11. private bool m_RightSafe = false;
  12. [SerializeField]
  13. private bool m_UpSafe = false;
  14. [SerializeField]
  15. private bool m_BottomSafe = false;
  16. public Transform[] autoHideTrans;
  17. protected override void CalcRect(Rect safeArea, ScreenOrientation orientation, int width, int height, out Vector2 min, out Vector2 max)
  18. {
  19. // 换算成u3d的屏幕坐标(左下角)
  20. float minX, minY, maxX, maxY;
  21. bool leftSafe, rightSafe, upSafe, bottomSafe;
  22. if (orientation == ScreenOrientation.PortraitUpsideDown)
  23. {
  24. leftSafe = m_RightSafe;
  25. rightSafe = m_LeftSafe;
  26. upSafe = m_BottomSafe;
  27. bottomSafe = m_UpSafe;
  28. }
  29. else if (orientation == ScreenOrientation.LandscapeLeft)
  30. {
  31. leftSafe = m_UpSafe;
  32. rightSafe = m_BottomSafe;
  33. upSafe = m_RightSafe;
  34. bottomSafe = m_LeftSafe;
  35. }
  36. else if (orientation == ScreenOrientation.LandscapeRight)
  37. {
  38. leftSafe = m_BottomSafe;
  39. rightSafe = m_UpSafe;
  40. upSafe = m_LeftSafe;
  41. bottomSafe = m_RightSafe;
  42. }
  43. else
  44. {
  45. leftSafe = m_LeftSafe;
  46. rightSafe = m_RightSafe;
  47. upSafe = m_UpSafe;
  48. bottomSafe = m_BottomSafe;
  49. }
  50. minX = (leftSafe ? safeArea.x : 0);
  51. minY = (bottomSafe ? safeArea.y : 0);
  52. maxX = (rightSafe ? (safeArea.x + safeArea.width) : width);
  53. maxY = (upSafe ? (safeArea.y + safeArea.height) : height);
  54. min = new Vector2(minX, minY);
  55. max = new Vector2(maxX, maxY);
  56. float deltaH = maxY - minY;
  57. if (autoHideTrans != null)
  58. {
  59. for (int idx = 0; idx < autoHideTrans.Length; idx++)
  60. {
  61. if (autoHideTrans[idx] != null)
  62. autoHideTrans[idx].gameObject.SetActive(deltaH < Screen.height);
  63. }
  64. }
  65. }
  66. }