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(); if (canvasScaler == null) canvasScaler = GetComponent(); 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; }