PadMaskView.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. namespace GFGGame
  4. {
  5. public class PadMaskView : MonoBehaviour
  6. {
  7. private static GameObject _ui;
  8. private Image BorderLeft;
  9. private Image BorderRight;
  10. /// <summary>
  11. /// 打开界面
  12. /// </summary>
  13. public static void Open()
  14. {
  15. var go = Resources.Load<GameObject>("UUI/Launcher/UIPadMask");
  16. _ui = GameObject.Instantiate(go);
  17. DontDestroyOnLoad(_ui);
  18. }
  19. /// <summary>
  20. /// 关闭界面
  21. /// </summary>
  22. /// <param name="toDestroy"></param>
  23. public static void Close()
  24. {
  25. GameObject.DestroyImmediate(_ui);
  26. _ui = null;
  27. }
  28. private void Start()
  29. {
  30. BorderLeft = _ui.transform.Find("BorderLeft").GetComponent<Image>();
  31. BorderRight = _ui.transform.Find("BorderRight").GetComponent<Image>();
  32. InitBorder();
  33. }
  34. private void InitBorder()
  35. {
  36. //这里做了最大宽度适配
  37. float targetWidth;
  38. float maxAspectRatio = 1080 * 1.0f / 1920;
  39. if (Screen.width * 1.0f / Screen.height > maxAspectRatio)
  40. {
  41. targetWidth = Screen.height * maxAspectRatio;
  42. }
  43. else
  44. {
  45. targetWidth = Screen.width;
  46. }
  47. float leftX = - targetWidth / 2;
  48. float rightX = -leftX;
  49. float maskWidth = (Screen.width - targetWidth) / 2;
  50. BorderLeft.rectTransform.anchoredPosition = new Vector2(leftX, 0);
  51. BorderRight.rectTransform.anchoredPosition = new Vector2(rightX, 0);
  52. BorderLeft.rectTransform.sizeDelta = new Vector2(maskWidth, BorderLeft.rectTransform.sizeDelta.y);
  53. BorderRight.rectTransform.sizeDelta = BorderLeft.rectTransform.sizeDelta;
  54. }
  55. }
  56. }