| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- using UnityEngine;
- using UnityEngine.UI;
- public class CanvasAutoAdapter : MonoBehaviour
- {
- public Canvas canvas;
- public CanvasScaler canvasScaler;
- public RectTransform safeAreaPanel; // 处理 Safe Area 适配的 UI 根对象
- void Start()
- {
- if (canvas == null)
- canvas = GetComponent<Canvas>();
- if (canvasScaler == null)
- canvasScaler = GetComponent<CanvasScaler>();
- ApplyCanvasScalerSettings();
- ApplySafeArea();
- }
- void ApplyCanvasScalerSettings()
- {
- if (canvasScaler == null) return;
- float screenRatio = (float)Screen.width / Screen.height; // 当前设备宽高比
- float referenceRatio = 1280f / 720f; // 游戏原始分辨率的宽高比
- if (screenRatio > referenceRatio)
- {
- // 设备比参考宽,调整高度适配
- canvasScaler.matchWidthOrHeight = 1.0f;
- }
- else
- {
- // 设备比参考窄,调整宽度适配
- canvasScaler.matchWidthOrHeight = 0.0f;
- }
- Debug.Log($"Screen Ratio: {screenRatio}, Match Mode: {canvasScaler.matchWidthOrHeight}");
- }
- void ApplySafeArea()
- {
- if (safeAreaPanel == null) return;
- Rect safeArea = Screen.safeArea;
- Vector2 anchorMin = safeArea.position;
- Vector2 anchorMax = safeArea.position + safeArea.size;
- anchorMin.x /= Screen.width;
- anchorMin.y /= Screen.height;
- anchorMax.x /= Screen.width;
- anchorMax.y /= Screen.height;
- safeAreaPanel.anchorMin = anchorMin;
- safeAreaPanel.anchorMax = anchorMax;
- Debug.Log($"Safe Area Applied: {safeArea}");
- }
- //void Update()
- //{
- // // 监听屏幕旋转或窗口大小变化
- // if (Screen.width != lastScreenWidth || Screen.height != lastScreenHeight)
- // {
- // lastScreenWidth = Screen.width;
- // lastScreenHeight = Screen.height;
- // ApplyCanvasScalerSettings();
- // ApplySafeArea();
- // }
- //}
- private int lastScreenWidth, lastScreenHeight;
- }
|