/**************************************************** 文件:FixScreenRatio.cs 作者:陶长春 邮箱:376248129@qq.com 日期:2025年3月13日 9:10:37 UnityVersion: 2021.3.13f1 功能:UI适配 *****************************************************/ using TFramework; using System.Collections; using UnityEngine; using System.Collections.Generic; using UnityEngine.UI; namespace TFramework { public class FixScreenRatio : MonoBehaviour { CanvasScaler canvasScaler; float rateW = 1.0f; float rateH = 1.0f; private int cachedWidth = 0; private int cachedHeight = 0; public static float windowRate = 1.0f; public static float screenRate = 1.0f; public static float width = 1920f; public static float height = 1080f; [System.NonSerialized] public bool IsUpdatePerFrame = true; private void Awake() { Screen.autorotateToPortrait = false; Screen.autorotateToPortraitUpsideDown = false; canvasScaler = GetComponent(); screenRate = width / height; } private void Update() { if (IsUpdatePerFrame) { if (cachedWidth != Screen.width || cachedHeight != Screen.height) { UpdateWhenScreenChange(); } } } public void UpdateWhenScreenChange() { cachedWidth = Screen.width; cachedHeight = Screen.height; Scale(); } void Scale() { rateW = Screen.width / width; rateH = Screen.height / height; if (rateW > rateH) { //以高度适配 windowRate = rateH; if (canvasScaler != null) { canvasScaler.matchWidthOrHeight = 1; } } else { //以宽度适配 windowRate = rateW; if (canvasScaler != null) { canvasScaler.matchWidthOrHeight = 0; } } } } }