| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- using UnityEngine;
- using UnityEngine.UI;
- namespace AdaptUI
- {
- [System.Serializable]
- public struct FontSizeData
- {
- public int fontSize;
- public FontSizeData(int size)
- {
- fontSize = size;
- }
- public bool IsValid() => fontSize > 0;
- }
- [ExecuteAlways]
- [RequireComponent(typeof(Text))]
- public class UIFontSizeAdapter : MonoBehaviour
- {
- [Header("默认字体大小")]
- public FontSizeData defaultFontSize;
- [Header("iPhone 字体大小")]
- public FontSizeData iPhoneFontSize;
- [Header("iPad 字体大小")]
- public FontSizeData iPadFontSize;
- private Text text;
- private bool isInitialized = false;
- private void Awake()
- {
- text = GetComponent<Text>();
- if (!isInitialized) return;
- ApplyFontSize();
- }
- #if UNITY_EDITOR
- private void Reset()
- {
- text = GetComponent<Text>();
- if (!isInitialized && text != null)
- {
- defaultFontSize = new FontSizeData(text.fontSize);
- iPhoneFontSize = new FontSizeData(text.fontSize);
- iPadFontSize = new FontSizeData(text.fontSize);
- isInitialized = true;
- Debug.Log("UIFontSizeAdapter: 初始化默认字体大小为 " + text.fontSize);
- }
- }
- #endif
- public void ApplyFontSize()
- {
- if (text == null) return;
- var type = DeviceTypeHelper.DetectDeviceType();
- int size = defaultFontSize.fontSize;
- switch (type)
- {
- case DeviceTypeHelper.DeviceType.iPhone:
- size = iPhoneFontSize.fontSize;
- break;
- case DeviceTypeHelper.DeviceType.iPad:
- size = iPadFontSize.fontSize;
- break;
- }
- text.fontSize = size;
- Debug.Log($"📌 应用字体大小: {size} (设备: {type})");
- }
- public void SetFontSize(bool isIpad, int size)
- {
- if (isIpad)
- iPadFontSize = new FontSizeData(size);
- else
- iPhoneFontSize = new FontSizeData(size);
- }
- public FontSizeData GetFontSize(bool isIpad)
- {
- return isIpad ? iPadFontSize : iPhoneFontSize;
- }
- }
- }
|