让UI完全按屏幕比例变化的方法
方法一:使用Aspect Ratio Fitter组件
这是最直接的方法,可以为整个Canvas或特定UI元素添加宽高比约束:
using UnityEngine;
using UnityEngine.UI;public class AspectRatioUI : MonoBehaviour
{private void Start(){// 为Canvas添加Aspect Ratio Fitter组件AspectRatioFitter aspectFitter = gameObject.AddComponent<AspectRatioFitter>();// 设置根据屏幕比例自动调整aspectFitter.aspectMode = AspectRatioFitter.AspectMode.FitInParent;// 或者固定特定比例// aspectFitter.aspectRatio = 16f / 9f; // 固定16:9// aspectFitter.aspectRatio = 4f / 3f; // 固定4:3}private void Update(){// 动态根据当前屏幕比例调整float currentAspect = (float)Screen.width / Screen.height;GetComponent<AspectRatioFitter>().aspectRatio = currentAspect;}
}
方法二:动态调整Canvas Scaler
通过代码动态调整Canvas Scaler的匹配值,让UI完全跟随屏幕比例:
using UnityEngine;
using UnityEngine.UI;public class DynamicAspectRatioScaler : MonoBehaviour
{private CanvasScaler canvasScaler;private float targetAspect = 16f / 9f; // 你的目标比例void Start(){canvasScaler = GetComponent<CanvasScaler>();UpdateAspectRatio();}void Update(){// 如果屏幕比例发生变化,更新UIif (Screen.width / (float)Screen.height != canvasScaler.matchWidthOrHeight){UpdateAspectRatio();}}void UpdateAspectRatio(){float currentAspect = (float)Screen.width / Screen.height;// 计算当前比例与目标比例的差异float aspectDifference = Mathf.Abs(currentAspect - targetAspect) / targetAspect;// 根据比例差异决定匹配宽度还是高度if (currentAspect > targetAspect){// 宽屏,匹配高度canvasScaler.matchWidthOrHeight = 1f;}else{// 窄屏,匹配宽度canvasScaler.matchWidthOrHeight = 0f;}Debug.Log($"屏幕比例: {currentAspect:F2}, 匹配模式: {(canvasScaler.matchWidthOrHeight == 0f ? "宽度" : "高度")}");}
}
方法三:完全比例适配脚本
这个脚本可以确保UI元素完全按照屏幕比例进行缩放和布局:
using UnityEngine;
using UnityEngine.UI;public class PerfectAspectRatioAdapter : MonoBehaviour
{[Header("参考比例设置")]public Vector2 referenceResolution = new Vector2(1920, 1080); // 16:9public float referenceAspect = 16f / 9f;private RectTransform canvasRect;private Vector2 lastScreenSize;void Start(){canvasRect = GetComponent<RectTransform>();lastScreenSize = new Vector2(Screen.width, Screen.height);AdaptToAspectRatio();}void Update(){Vector2 currentScreenSize = new Vector2(Screen.width, Screen.height);if (currentScreenSize != lastScreenSize){AdaptToAspectRatio();lastScreenSize = currentScreenSize;}}void AdaptToAspectRatio(){float currentAspect = (float)Screen.width / Screen.height;// 计算缩放比例float scaleFactor = CalculateScaleFactor(currentAspect);// 应用缩放CanvasScaler scaler = GetComponent<CanvasScaler>();if (scaler != null){scaler.scaleFactor = scaleFactor;}// 调整Canvas大小以匹配屏幕比例if (canvasRect != null){canvasRect.sizeDelta = new Vector2(Screen.width, Screen.height);}// 通知所有子UI元素更新布局LayoutRebuilder.ForceRebuildLayoutImmediate(canvasRect);Debug.Log($"当前比例: {currentAspect:F4}, 缩放因子: {scaleFactor:F4}");}float CalculateScaleFactor(float currentAspect){if (currentAspect > referenceAspect){// 宽屏,基于高度缩放return (float)Screen.height / referenceResolution.y;}else{// 窄屏,基于宽度缩放return (float)Screen.width / referenceResolution.x;}}// 获取当前屏幕比例public float GetCurrentAspectRatio(){return (float)Screen.width / Screen.height;}// 手动设置为特定比例(用于测试)public void SetTestAspectRatio(float aspectRatio){// 这里可以用于测试不同比例下的表现AdaptToAspectRatio();}
}
方法四:为特定UI区域创建比例容器
如果你只需要部分UI区域按比例变化,可以创建一个比例容器:
using UnityEngine;
using UnityEngine.UI;public class AspectRatioContainer : MonoBehaviour
{[Header("目标比例")]public float targetAspectRatio = 16f / 9f;private RectTransform rectTransform;private Canvas canvas;void Start(){rectTransform = GetComponent<RectTransform>();canvas = GetComponentInParent<Canvas>();UpdateContainerAspect();}void Update(){UpdateContainerAspect();}void UpdateContainerAspect(){if (rectTransform == null || canvas == null) return;float canvasWidth = canvas.pixelRect.width;float canvasHeight = canvas.pixelRect.height;float canvasAspect = canvasWidth / canvasHeight;if (canvasAspect > targetAspectRatio){// 画布比目标宽,限制宽度float targetWidth = canvasHeight * targetAspectRatio;rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, targetWidth);rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, canvasHeight);}else{// 画布比目标窄,限制高度float targetHeight = canvasWidth / targetAspectRatio;rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, canvasWidth);rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, targetHeight);}}
}
使用建议
-
方法一适合简单的固定比例需求
-
方法二适合需要动态切换匹配模式的复杂项目
-
方法三提供最完整的比例适配控制
-
方法四适合只需要部分UI区域保持特定比例的情况
测试不同比例
你可以在Game窗口中选择不同的分辨率来测试效果,或者使用代码模拟:
// 测试脚本 - 切换不同比例
public class AspectRatioTester : MonoBehaviour
{public void Set16_9() { SetResolution(1920, 1080); }public void Set4_3() { SetResolution(1024, 768); }public void Set21_9() { SetResolution(2560, 1080); }void SetResolution(int width, int height){Screen.SetResolution(width, height, false);}
}
这些方法可以确保你的UI在不同屏幕比例下都能保持正确的布局和比例关系。
DEEP SEEK生成
