hch
2 天以前 6b311b24ce279b92c7e52532f0d4b82983808701
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
/// <summary>
/// 图片组件类型枚举
/// </summary>
public enum ImageComponentType
{
    None = 0,
    Image = 1,
    ImageEx = 2
}
 
/// <summary>
/// 单个语言的图片排版和适配数据节点
/// </summary>
[Serializable]
public class ImageLanguageConfigItem
{
    [Header("RectTransform 配置")]
    public Vector2 anchoredPosition = Vector2.zero;
    public Vector2 sizeDelta = new Vector2(100f, 100f);
    public Vector2 anchorMin = new Vector2(0.5f, 0.5f);
    public Vector2 anchorMax = new Vector2(0.5f, 0.5f);
    public Vector2 pivot = new Vector2(0.5f, 0.5f);
    public Vector3 localScale = Vector3.one;
    public Vector3 localRotation = Vector3.zero;
 
    [Header("Image 配置")]
    public bool enabled = true;
    public Color color = Color.white;
    public Image.Type type = Image.Type.Simple;
    public bool fillCenter = true;
    public Image.FillMethod fillMethod = Image.FillMethod.Horizontal;
    public float fillAmount = 1f;
    public int fillOrigin = 0;
    public bool preserveAspect = true;
    public float alphaHitTestMinimumThreshold = 0f;
    public bool useSpriteMesh = false;
    public float pixelsPerUnitMultiplier = 1f;
 
    public void ApplyToRectTransform(RectTransform rt)
    {
        if (rt == null) return;
        rt.anchorMin = anchorMin;
        rt.anchorMax = anchorMax;
        rt.pivot = pivot;
        rt.anchoredPosition = anchoredPosition;
        rt.sizeDelta = sizeDelta;
        rt.localScale = localScale;
        rt.localRotation = Quaternion.Euler(localRotation);
    }
 
    public void ReadFromRectTransform(RectTransform rt)
    {
        if (rt == null) return;
        anchorMin = rt.anchorMin;
        anchorMax = rt.anchorMax;
        pivot = rt.pivot;
        anchoredPosition = rt.anchoredPosition;
        sizeDelta = rt.sizeDelta;
        localScale = rt.localScale;
        localRotation = rt.localRotation.eulerAngles;
    }
 
    public void ApplyToImage(Image img)
    {
        if (img == null) return;
        img.color = color;
        img.type = type;
        img.fillCenter = fillCenter;
        img.fillMethod = fillMethod;
        img.fillAmount = fillAmount;
        img.fillOrigin = fillOrigin;
        img.preserveAspect = preserveAspect;
        try
        {
            img.alphaHitTestMinimumThreshold = alphaHitTestMinimumThreshold;
        }
        catch (InvalidOperationException)
        {
            // 纹理不可读或未使用 Crunch 压缩时跳过,这是 Unity 内部限制
        }
        img.useSpriteMesh = useSpriteMesh;
        img.pixelsPerUnitMultiplier = pixelsPerUnitMultiplier;
    }
 
    public void ReadFromImage(Image img)
    {
        if (img == null) return;
        color = img.color;
        type = img.type;
        fillCenter = img.fillCenter;
        fillMethod = img.fillMethod;
        fillAmount = img.fillAmount;
        fillOrigin = img.fillOrigin;
        preserveAspect = img.preserveAspect;
        alphaHitTestMinimumThreshold = img.alphaHitTestMinimumThreshold;
        useSpriteMesh = img.useSpriteMesh;
        pixelsPerUnitMultiplier = img.pixelsPerUnitMultiplier;
    }
 
    public ImageLanguageConfigItem Clone() => (ImageLanguageConfigItem)MemberwiseClone();
}
 
/// <summary>
/// 支持 Unity 序列化的字典
/// </summary>
[Serializable]
public class ImageLanguageConfigDictionary
{
    public List<string> keys = new List<string>();
    public List<ImageLanguageConfigItem> values = new List<ImageLanguageConfigItem>();
 
    public ImageLanguageConfigItem Get(string key)
    {
        if (string.IsNullOrEmpty(key)) return null;
        int index = keys.IndexOf(key);
        return index >= 0 ? values[index] : null;
    }
 
    public void Set(string key, ImageLanguageConfigItem value)
    {
        int index = keys.IndexOf(key);
        if (index >= 0) values[index] = value;
        else
        {
            keys.Add(key);
            values.Add(value);
        }
    }
 
    public bool ContainsKey(string key) => keys.Contains(key);
 
    public void Remove(string key)
    {
        int index = keys.IndexOf(key);
        if (index >= 0)
        {
            keys.RemoveAt(index);
            values.RemoveAt(index);
        }
    }
}
 
/// <summary>
/// 多语言图片排版适配器
/// </summary>
[RequireComponent(typeof(RectTransform))]
public class ImageLanguageAdapter : MonoBehaviour
{
    public const string DefaultLangId = "default";
 
    [SerializeField, Tooltip("语言配置字典")]
    private ImageLanguageConfigDictionary m_LanguageConfigs = new ImageLanguageConfigDictionary();
 
    [SerializeField, Tooltip("目标图片组件类型")]
    private ImageComponentType m_TargetImageType = ImageComponentType.None;
 
    [SerializeField, Tooltip("关联的图片组件引用")]
    private Component m_TargetImageComponent;
 
    private bool m_IsApplied = false;
 
    public ImageComponentType TargetImageType
    {
        get => m_TargetImageType;
        set => m_TargetImageType = value;
    }
    public Component TargetImageComponent
    {
        get => m_TargetImageComponent;
        set => m_TargetImageComponent = value;
    }
    public ImageLanguageConfigDictionary LanguageConfigs => m_LanguageConfigs;
 
    private void Awake() => DetectTargetComponent();
 
    private void OnEnable()
    {
        if (!Application.isPlaying || !m_IsApplied)
        {
            string langId = Application.isPlaying ? Language.Id : DefaultLangId;
            ApplyConfig(langId);
        }
    }
 
#if UNITY_EDITOR
    private void Reset()
    {
        DetectTargetComponent();
        if (!HasConfig(DefaultLangId)) ReadCurrentToConfig(DefaultLangId);
    }
#endif
 
    public ImageLanguageConfigItem GetConfig(string languageId) => m_LanguageConfigs.Get(languageId);
    public void SetConfig(string languageId, ImageLanguageConfigItem config) => m_LanguageConfigs.Set(languageId, config);
    public void RemoveConfig(string languageId) => m_LanguageConfigs.Remove(languageId);
    public bool HasConfig(string languageId) => m_LanguageConfigs.ContainsKey(languageId);
    public List<string> GetConfiguredLanguages() => new List<string>(m_LanguageConfigs.keys);
 
    public void ApplyConfig(string languageId)
    {
        var config = GetConfig(languageId);
        if (config == null) return;
 
        config.ApplyToRectTransform(GetComponent<RectTransform>());
 
        if (m_TargetImageComponent != null)
        {
            m_TargetImageComponent.gameObject.SetActive(config.enabled);
        }
 
        if (m_TargetImageComponent is Image img)
        {
            config.ApplyToImage(img);
        }
 
        m_IsApplied = true;
    }
 
    public void ReadCurrentToConfig(string languageId)
    {
        var config = new ImageLanguageConfigItem();
        config.ReadFromRectTransform(GetComponent<RectTransform>());
 
        if (m_TargetImageComponent is Image img)
        {
            config.ReadFromImage(img);
        }
 
        SetConfig(languageId, config);
    }
 
    public static string GetLanguageShowName(string languageId)
    {
        if (Language.languageShowDict != null && Language.languageShowDict.TryGetValue(languageId, out string showName))
            return showName;
        return languageId;
    }
 
    private void DetectTargetComponent()
    {
        if (m_TargetImageComponent != null)
        {
            DetermineImageType(m_TargetImageComponent);
            return;
        }
 
        m_TargetImageComponent = GetComponent<ImageEx>() ?? GetComponentInChildren<ImageEx>(true) as Component
                                ?? GetComponent<Image>() ?? GetComponentInChildren<Image>(true) as Component;
 
        DetermineImageType(m_TargetImageComponent);
    }
 
    private void DetermineImageType(Component component)
    {
        m_TargetImageType = component switch
        {
            ImageEx _ => ImageComponentType.ImageEx,
            Image _ => ImageComponentType.Image,
            _ => ImageComponentType.None
        };
    }
 
#if UNITY_EDITOR
    [ContextMenu("刷新组件检测")]
    public void Editor_ForceRefreshDetection()
    {
        DetectTargetComponent();
        UnityEditor.EditorUtility.SetDirty(this);
    }
 
    [ContextMenu("读取当前配置")]
    public void Editor_ReadCurrentConfig()
    {
        ReadCurrentToConfig(DefaultLangId);
        UnityEditor.EditorUtility.SetDirty(this);
    }
 
    [ContextMenu("应用默认配置")]
    public void Editor_ApplyDefaultConfig() => ApplyConfig(DefaultLangId);
#endif
}