CanvasAutoAdapter.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. public class CanvasAutoAdapter : MonoBehaviour
  4. {
  5. public Canvas canvas;
  6. public CanvasScaler canvasScaler;
  7. public RectTransform safeAreaPanel; // 处理 Safe Area 适配的 UI 根对象
  8. void Start()
  9. {
  10. if (canvas == null)
  11. canvas = GetComponent<Canvas>();
  12. if (canvasScaler == null)
  13. canvasScaler = GetComponent<CanvasScaler>();
  14. ApplyCanvasScalerSettings();
  15. ApplySafeArea();
  16. }
  17. void ApplyCanvasScalerSettings()
  18. {
  19. if (canvasScaler == null) return;
  20. float screenRatio = (float)Screen.width / Screen.height; // 当前设备宽高比
  21. float referenceRatio = 1280f / 720f; // 游戏原始分辨率的宽高比
  22. if (screenRatio > referenceRatio)
  23. {
  24. // 设备比参考宽,调整高度适配
  25. canvasScaler.matchWidthOrHeight = 1.0f;
  26. }
  27. else
  28. {
  29. // 设备比参考窄,调整宽度适配
  30. canvasScaler.matchWidthOrHeight = 0.0f;
  31. }
  32. Debug.Log($"Screen Ratio: {screenRatio}, Match Mode: {canvasScaler.matchWidthOrHeight}");
  33. }
  34. void ApplySafeArea()
  35. {
  36. if (safeAreaPanel == null) return;
  37. Rect safeArea = Screen.safeArea;
  38. Vector2 anchorMin = safeArea.position;
  39. Vector2 anchorMax = safeArea.position + safeArea.size;
  40. anchorMin.x /= Screen.width;
  41. anchorMin.y /= Screen.height;
  42. anchorMax.x /= Screen.width;
  43. anchorMax.y /= Screen.height;
  44. safeAreaPanel.anchorMin = anchorMin;
  45. safeAreaPanel.anchorMax = anchorMax;
  46. Debug.Log($"Safe Area Applied: {safeArea}");
  47. }
  48. //void Update()
  49. //{
  50. // // 监听屏幕旋转或窗口大小变化
  51. // if (Screen.width != lastScreenWidth || Screen.height != lastScreenHeight)
  52. // {
  53. // lastScreenWidth = Screen.width;
  54. // lastScreenHeight = Screen.height;
  55. // ApplyCanvasScalerSettings();
  56. // ApplySafeArea();
  57. // }
  58. //}
  59. private int lastScreenWidth, lastScreenHeight;
  60. }