Unity - Font Pruner
2019-05-28 / 3 min read
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using AssetBundleBrowser.AssetBundlePacker;
using UnityEditor;
using UnityEditor.VersionControl;
using UnityEngine;
using Debug = UnityEngine.Debug;
<!-- more -->
public class FontPrunerEditor : EditorWindow
{
[MenuItem("Tools/Font Small")]
static void StartWindow()
{
EditorWindow.GetWindow<FontPrunerEditor>();
}
private Font fontAsset;
private TextAsset charsList;
private string jarAsset;
private const int TimeOut = 100000;
private string workingPath = string.Empty;
private const string jar_file = "sfnttool.jar";
void OnEnable()
{
var importers = PluginImporter.GetAllImporters();
jarAsset = importers.First(t => t.assetPath.Contains(jar_file)).assetPath;
workingPath = Directory.GetParent(jarAsset).Parent.ToString();
Debug.Log(workingPath);
}
void OnGUI()
{
fontAsset = (Font) EditorGUILayout.ObjectField("字体", fontAsset, typeof(Font), false);
charsList = (TextAsset) EditorGUILayout.ObjectField("字符集", charsList, typeof(TextAsset), false);
GUILayout.Space(50);
if (GUILayout.Button("过滤非法字符"))
{
var str = charsList.text;
var newStr = Regex.Replace(str, @"\p{Cs}", "");
Debug.Log(newStr);
var path = EditorCommon.RelativeToAbsolutePath(AssetDatabase.GetAssetPath(charsList));
File.Copy(path, path + ".bak",true);
File.WriteAllText(path, newStr);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(charsList));
if (EditorUtility.DisplayDialog("成功", "已经成功过滤非法字符,旧文件已保存为同目录下.bak文件", "ok"))
{
}
}
GUILayout.Space(5);
if (GUILayout.Button("Go !"))
{
DoProcess();
}
}
private void DoProcess()
{
var fileName = "java";
//java -jar sfnttool.jar -s '需要提取的字体' 源字体库 导出的最终字体库
var commandLine = " -jar bin/" + jar_file + " -c " +
EditorCommon.RelativeToAbsolutePath(AssetDatabase.GetAssetPath(charsList)) + " " +
EditorCommon.RelativeToAbsolutePath(AssetDatabase.GetAssetPath(fontAsset)) + " " +
Application.dataPath + "/" + fontAsset.name + "_new.ttf";
Process process = Process.Start(
new ProcessStartInfo(fileName, commandLine)
{
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = false,
WorkingDirectory = workingPath,
// http://stackoverflow.com/questions/16803748/how-to-decode-cmd-output-correctly
// Default = 65533, ASCII = ?, Unicode = nothing works at all, UTF-8 = 65533, UTF-7 = 242 = WORKS!, UTF-32 = nothing works at all
StandardOutputEncoding = Encoding.GetEncoding(850)
});
if (!process.WaitForExit(TimeOut))
{
Debug.LogWarning("FontPruner took too long to finish. Killing operation.");
process.Kill();
}
string error = process.StandardError.ReadToEnd();
if (!string.IsNullOrEmpty(error))
{
Debug.LogError(error);
}
string output = process.StandardOutput.ReadToEnd();
if (!string.IsNullOrEmpty(output))
{
Debug.Log(output);
}
}
}