PadMaskView.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. namespace GFGGame
  5. {
  6. public class PadMaskView : MonoBehaviour
  7. {
  8. private static GameObject _ui;
  9. private Image BorderLeft;
  10. private Image BorderRight;
  11. /// <summary>
  12. /// 打开界面
  13. /// </summary>
  14. public static void Open()
  15. {
  16. CoroutineHelper.Instance.StartCoroutine(LoadPadMaskAsync());
  17. }
  18. /// <summary>
  19. /// 异步加载 UIPadMask 资源
  20. /// </summary>
  21. private static IEnumerator LoadPadMaskAsync()
  22. {
  23. // 异步加载资源
  24. var resourceRequest = Resources.LoadAsync<GameObject>("UUI/Launcher/UIPadMask");
  25. // 等待资源加载完成
  26. yield return new WaitUntil(() => resourceRequest.isDone);
  27. // 在资源加载完成后实例化 UI
  28. if (resourceRequest.asset != null)
  29. {
  30. _ui = GameObject.Instantiate(resourceRequest.asset as GameObject);
  31. DontDestroyOnLoad(_ui);
  32. }
  33. else
  34. {
  35. Debug.LogError("Failed to load UIPadMask.");
  36. }
  37. }
  38. /// <summary>
  39. /// 关闭界面
  40. /// </summary>
  41. /// <param name="toDestroy"></param>
  42. public static void Close()
  43. {
  44. GameObject.DestroyImmediate(_ui);
  45. _ui = null;
  46. }
  47. private void Start()
  48. {
  49. BorderLeft = _ui.transform.Find("BorderLeft").GetComponent<Image>();
  50. BorderRight = _ui.transform.Find("BorderRight").GetComponent<Image>();
  51. InitBorder();
  52. }
  53. private void InitBorder()
  54. {
  55. //这里做了最大宽度适配
  56. float targetWidth;
  57. float maxAspectRatio = 1080 * 1.0f / 1920;
  58. if (Screen.width * 1.0f / Screen.height > maxAspectRatio)
  59. {
  60. targetWidth = Screen.height * maxAspectRatio;
  61. }
  62. else
  63. {
  64. targetWidth = Screen.width;
  65. }
  66. float leftX = -targetWidth / 2;
  67. float rightX = -leftX;
  68. float maskWidth = (Screen.width - targetWidth) / 2;
  69. BorderLeft.rectTransform.anchoredPosition = new Vector2(leftX, 0);
  70. BorderRight.rectTransform.anchoredPosition = new Vector2(rightX, 0);
  71. BorderLeft.rectTransform.sizeDelta = new Vector2(maskWidth, BorderLeft.rectTransform.sizeDelta.y);
  72. BorderRight.rectTransform.sizeDelta = BorderLeft.rectTransform.sizeDelta;
  73. }
  74. }
  75. }