UIFontSizeAdapter.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. ApplyFontSize();
  32. }
  33. #if UNITY_EDITOR
  34. private void Reset()
  35. {
  36. text = GetComponent<Text>();
  37. if (!isInitialized && text != null)
  38. {
  39. defaultFontSize = new FontSizeData(text.fontSize);
  40. iPhoneFontSize = new FontSizeData(text.fontSize);
  41. iPadFontSize = new FontSizeData(text.fontSize);
  42. isInitialized = true;
  43. Debug.Log("UIFontSizeAdapter: 初始化默认字体大小为 " + text.fontSize);
  44. }
  45. }
  46. #endif
  47. public void ApplyFontSize()
  48. {
  49. if (text == null) return;
  50. var type = DeviceTypeHelper.DetectDeviceType();
  51. int size = defaultFontSize.fontSize;
  52. switch (type)
  53. {
  54. case DeviceTypeHelper.DeviceType.iPhone:
  55. size = iPhoneFontSize.fontSize;
  56. break;
  57. case DeviceTypeHelper.DeviceType.iPad:
  58. size = iPadFontSize.fontSize;
  59. break;
  60. }
  61. text.fontSize = size;
  62. Debug.Log($"📌 应用字体大小: {size} (设备: {type})");
  63. }
  64. public void SetFontSize(bool isIpad, int size)
  65. {
  66. if (isIpad)
  67. iPadFontSize = new FontSizeData(size);
  68. else
  69. iPhoneFontSize = new FontSizeData(size);
  70. }
  71. public FontSizeData GetFontSize(bool isIpad)
  72. {
  73. return isIpad ? iPadFontSize : iPhoneFontSize;
  74. }
  75. }
  76. }