当前位置: 首页 > news >正文

让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);}}
}

使用建议

  1. 方法一适合简单的固定比例需求

  2. 方法二适合需要动态切换匹配模式的复杂项目

  3. 方法三提供最完整的比例适配控制

  4. 方法四适合只需要部分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生成

http://www.dtcms.com/a/600598.html

相关文章:

  • 结项报告完整版:Apache SeaTunnel 支持 Flink 引擎 Schema Evolution 功能
  • 微服务生态组件之Spring Cloud LoadBalancer详解和源码分析
  • 重庆长寿网站设计公司哪家专业网站跳转微信链接
  • 阿里云域名DNS解析URL转发不支持HTTPS?
  • leetcode 2654. 使数组所有元素变成 1 的最少操作次数 中等
  • AI取名大师 | PM2 部署 Bun.js 应用及配置 Let‘s Encrypt 免费 HTTPS 证书
  • 结项报告完整版 | Apache SeaTunnel支持metalake开发
  • 【cursor】进阶技巧Rules
  • WebServer05
  • 【数据分析-Excel】常用函数汇总
  • 深入理解MySQL事务隔离级别与锁机制(从ACID到MVCC的全面解析)
  • RabbitMQ应用(1)
  • .NET驾驭Excel之力:Excel应用程序的创建与管理
  • Unity2.5D视角肉鸽项目架构
  • JAVA和C#的语法对比
  • WPS Excel 图表
  • 电商网站开发需要掌握哪些知识技能品牌设计和vi设计有什么区别
  • Spring 框架整合 JUnit 单元测试——包含完整执行流程
  • .NET驾驭Excel之力:自动化数据处理 - 开篇概述与环境准备
  • 多站点网站群的建设与管理识图搜索在线 照片识别
  • C++ builder xe 用imageen组件ImageEnView1合并多个图片导出一个pdf
  • 深度拆解汽车制造系统设计:用 Java + 设计模式打造高扩展性品牌 - 车型动态生成架构
  • 客户端VS前端VS后端
  • 西安企业网站建设哪家好hs网站推广
  • 【宝塔面板】监控、日志、任务与安全设置
  • RPA财务机器人落地指南:治理架构、流程优化与风险防控
  • GitHub Agent HQ正式发布,构建开放智能体生态
  • XML节点SelectSingleNode(“msbuild:DebugType“ 为什么要加msbuild
  • 【GitHub热门项目】(2025-11-12)
  • 【RAG评测方案汇总】GitHub开源工具全览