UIFontSizeAdapter.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. namespace AdaptUI
  4. {
  5. [System.Serializable]
  6. public struct FontSizeData
  7. {
  8. public int fontSize;
  9. public FontSizeData(int size)
  10. {
  11. fontSize = size;
  12. }
  13. public bool IsValid() => fontSize > 0;
  14. }
  15. [ExecuteAlways]
  16. [RequireComponent(typeof(Text))]
  17. public class UIFontSizeAdapter : MonoBehaviour
  18. {
  19. [Header("默认字体大小")]
  20. public FontSizeData defaultFontSize;
  21. [Header("iPhone 字体大小")]
  22. public FontSizeData iPhoneFontSize;
  23. [Header("iPad 字体大小")]
  24. public FontSizeData iPadFontSize;
  25. private Text text;
  26. private bool isInitialized = false;
  27. private void Awake()
  28. {
  29. text = GetComponent<Text>();
  30. // if (!isInitialized) return;
  31. #if UNITY_EDITOR
  32. if (!isInitialized)
  33. {
  34. // Debug.Log("UICanvasScalerAdaptive: 未初始化,跳过 ApplyScaler()");
  35. if (Application.isPlaying)
  36. ApplyFontSize();
  37. return;
  38. }
  39. #endif
  40. ApplyFontSize();
  41. }
  42. #if UNITY_EDITOR
  43. private void Reset()
  44. {
  45. text = GetComponent<Text>();
  46. if (!isInitialized && text != null)
  47. {
  48. defaultFontSize = new FontSizeData(text.fontSize);
  49. iPhoneFontSize = new FontSizeData(text.fontSize);
  50. iPadFontSize = new FontSizeData(text.fontSize);
  51. isInitialized = true;
  52. Debug.Log("UIFontSizeAdapter: 初始化默认字体大小为 " + text.fontSize);
  53. }
  54. }
  55. #endif
  56. public void ApplyFontSize()
  57. {
  58. if (text == null) return;
  59. var type = DeviceTypeHelper.DetectDeviceType();
  60. int size = defaultFontSize.fontSize;
  61. switch (type)
  62. {
  63. case DeviceTypeHelper.DeviceType.iPhone:
  64. size = iPhoneFontSize.fontSize;
  65. break;
  66. case DeviceTypeHelper.DeviceType.iPad:
  67. size = iPadFontSize.fontSize;
  68. break;
  69. }
  70. text.fontSize = size;
  71. Debug.Log($"📌 应用字体大小: {size} (设备: {type})");
  72. }
  73. public void SetFontSize(bool isIpad, int size)
  74. {
  75. if (isIpad)
  76. iPadFontSize = new FontSizeData(size);
  77. else
  78. iPhoneFontSize = new FontSizeData(size);
  79. }
  80. public FontSizeData GetFontSize(bool isIpad)
  81. {
  82. return isIpad ? iPadFontSize : iPhoneFontSize;
  83. }
  84. }
  85. }