Add system font matcher.

This commit is contained in:
2023-02-02 18:35:18 +08:00
parent bd256ba1a6
commit b407ba88c4
17 changed files with 792 additions and 17 deletions

View File

@@ -1,6 +1,9 @@
using System.Collections.Generic;
using Cryville.Common.Font;
using System;
using System.Reflection;
using TMPro;
using UnityEngine;
using UnityEngine.TextCore.LowLevel;
using UnityEngine.TextCore.Text;
using IFont = UnityEngine.Font;
@@ -8,23 +11,29 @@ namespace Cryville.Common.Unity.UI {
[RequireComponent(typeof(TextMeshProUGUI))]
public class TMPAutoFont : MonoBehaviour {
public static Shader DefaultShader;
public static readonly List<string> Fonts = new List<string> {
"Arial",
};
public static FontManager FontManager;
static FontAsset _font;
TextMeshProUGUI _text;
[SerializeField]
Shader m_shader;
void Awake() {
if (FontManager == null) return;
_text = GetComponent<TextMeshProUGUI>();
if (_font == null) {
var _ifont = new IFont("C:/Windows/Fonts/arial.ttf");
_font = FontAsset.CreateFontAsset(_ifont);
if (m_shader) _font.material.shader = m_shader;
else if (DefaultShader) _font.material.shader = DefaultShader;
foreach (var typeface in FontManager.MatchScript()) {
try {
var _ifont = new IFont(typeface.File.FullName);
_font = (FontAsset)typeof(FontAsset).GetMethod("CreateFontAsset", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { typeof(IFont), typeof(int), typeof(int), typeof(int), typeof(GlyphRenderMode), typeof(int), typeof(int), typeof(AtlasPopulationMode), typeof(bool) },
null).Invoke(null, new object[] { _ifont, typeface.IndexInFile, 90, 9, GlyphRenderMode.SDFAA, 1024, 1024, Type.Missing, Type.Missing });
break;
}
catch (Exception) { }
}
}
_text.font = _font;
if (m_shader) _font.material.shader = m_shader;
else if (DefaultShader) _font.material.shader = DefaultShader;
}
}
}