com.soviby.unity.ui.ugui-to.../Assets/Editor/Entity/TextMeshProEntity.cs
2024-12-03 13:05:13 +08:00

109 lines
3.9 KiB
C#

#if UNITY_EDITOR
using Sirenix.OdinInspector;
using Sirenix.Utilities;
using System.Linq;
using TMPro;
using Unity.Mathematics;
using UnityEditor;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.UI;
using static UguiToolkit.Editor.LayoutInfo;
namespace UguiToolkit.Editor
{
public class TextMeshProEntity : BaseEntity<TextMeshProUGUI, LayoutInfo.TextInfo>
{
private TextMeshProUGUI m_previewText;
public override void ApplyTransform(Transform tf)
{
var position = ElementInfo.Position;
tf.position = StageManager.Instance.PrefabContentsRoot.transform.TransformPoint(new Vector3(position.x, position.y, 0));
tf.rotation = Quaternion.identity;
}
protected override void OnApplyData(TextMeshProUGUI ui)
{
ui.text = ElementInfo.text;
ui.fontSize = (int)ElementInfo.size;
ui.color = ElementInfo.color;
ui.alignment = TextAlignmentOptions.Center;
SetTMPByTextInfo(ui, ElementInfo);
}
public override void InitPreview()
{
if (ElementInfo == null) return;
if (!TryGetComponent<TextMeshProUGUI>(out m_previewText))
{
m_previewText = gameObject.AddComponent<TextMeshProUGUI>();
}
OnApplyData(m_previewText);
ApplyTransform(transform);
}
private static void SetTMPByTextInfo(TextMeshProUGUI ui, LayoutInfo.TextInfo textInfo)
{
// TODO: ×ÔÐÐÀ©Õ¹
if (GetTextFontPreset(textInfo, out var textFontPreset))
{
ui.font = textFontPreset.tmpAsset;
if (!string.IsNullOrEmpty(textFontPreset.materialPreset))
{
var materialPresets = TMPro.EditorUtilities.TMP_EditorUtility.FindMaterialReferences(textFontPreset.tmpAsset);
if (materialPresets != null)
{
var material = materialPresets.FirstOrDefault((material) => {
if (material.name == textFontPreset.materialPreset) return true;
return false;
});
if (material) ui.fontMaterial = material;
}
}
var rectTransform = ui.rectTransform;
rectTransform.sizeDelta = new Vector2(textInfo.w + textFontPreset.sizeOffset.x, textInfo.h + textFontPreset.sizeOffset.y);
}
}
private static bool GetTextFontPreset(LayoutInfo.TextInfo textInfo, out TextFontPresetOfUnity textFontPreset)
{
float CalcColorDifference(in Color color1, in Color color2)
{
return math.abs(color1.r - color2.r) * 255 + math.abs(color1.g - color2.g) * 255 + math.abs(color1.b - color2.b) * 255;
}
textFontPreset = null;
var setting = GlobalManager.Instance.setting;
if (setting != null && setting.textFontList != null)
{
foreach (var textFontInfoOfPsd in setting.textFontList)
{
if (textFontInfoOfPsd.fontNameOfPsd != null && textFontInfoOfPsd.fontNameOfPsd.Contains(textInfo.font))
{
if (textFontInfoOfPsd.stroke)
{
if (!textInfo.IsStroke) continue;
if (!textFontInfoOfPsd.allStrokeColor)
{
if (CalcColorDifference(textFontInfoOfPsd.strokeColor ,textInfo.strokeColor) > textFontInfoOfPsd.strokeColorThreshold) continue;
}
}
textFontPreset = textFontInfoOfPsd;
return true;
}
}
}
return false;
}
}
}
#endif