Unity 框架

FixScreenRatio.cs 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /****************************************************
  2. 文件:FixScreenRatio.cs
  3. 作者:陶长春
  4. 邮箱:376248129@qq.com
  5. 日期:2025年3月13日 9:10:37
  6. UnityVersion: 2021.3.13f1
  7. 功能:UI适配
  8. *****************************************************/
  9. using TFramework;
  10. using System.Collections;
  11. using UnityEngine;
  12. using System.Collections.Generic;
  13. using UnityEngine.UI;
  14. namespace TFramework
  15. {
  16. public class FixScreenRatio : MonoBehaviour
  17. {
  18. CanvasScaler canvasScaler;
  19. float rateW = 1.0f;
  20. float rateH = 1.0f;
  21. private int cachedWidth = 0;
  22. private int cachedHeight = 0;
  23. public static float windowRate = 1.0f;
  24. public static float screenRate = 1.0f;
  25. public static float width = 1920f;
  26. public static float height = 1080f;
  27. [System.NonSerialized]
  28. public bool IsUpdatePerFrame = true;
  29. private void Awake()
  30. {
  31. Screen.autorotateToPortrait = false;
  32. Screen.autorotateToPortraitUpsideDown = false;
  33. canvasScaler = GetComponent<CanvasScaler>();
  34. screenRate = width / height;
  35. }
  36. private void Update()
  37. {
  38. if (IsUpdatePerFrame)
  39. {
  40. if (cachedWidth != Screen.width || cachedHeight != Screen.height)
  41. {
  42. UpdateWhenScreenChange();
  43. }
  44. }
  45. }
  46. public void UpdateWhenScreenChange()
  47. {
  48. cachedWidth = Screen.width;
  49. cachedHeight = Screen.height;
  50. Scale();
  51. }
  52. void Scale()
  53. {
  54. rateW = Screen.width / width;
  55. rateH = Screen.height / height;
  56. if (rateW > rateH)
  57. {
  58. //以高度适配
  59. windowRate = rateH;
  60. if (canvasScaler != null)
  61. {
  62. canvasScaler.matchWidthOrHeight = 1;
  63. }
  64. }
  65. else
  66. {
  67. //以宽度适配
  68. windowRate = rateW;
  69. if (canvasScaler != null)
  70. {
  71. canvasScaler.matchWidthOrHeight = 0;
  72. }
  73. }
  74. }
  75. }
  76. }