[Unity Editor] 基于BMFont創(chuàng)建美術(shù)(靜態(tài))字

1、背景

??馬上要做戰(zhàn)斗跳字了,提前調(diào)研下美術(shù)字的制作。
??使用美術(shù)字可以實(shí)現(xiàn)很好表現(xiàn)效果,并獲得不錯(cuò)的性能,比如:規(guī)避掉描邊、Shadow的消耗。

2、BMFont使用

??參考文章中寫的已經(jīng)很詳細(xì)了,這里僅列舉幾個(gè)不易發(fā)現(xiàn)的地方備忘。

  • 支持中文
    [Options - Font settings] Charset處,勾選Unicode(雖然它是默認(rèn)選中的)。

  • 設(shè)置導(dǎo)出紋理格式
    [Options - Export options] Textures處,可以指定導(dǎo)出紋理為PNG。
    在物理存儲上PNG比Tga小很多,而且在Unity中導(dǎo)入的效率也會更高。

  • 查看字符碼
    界面上選中字符,在右下角的數(shù)字中m:n,m就是字符碼

    字符碼

  • 導(dǎo)入字符的Icon
    這里只想說,它這按鈕做的太不明顯了Orz

    導(dǎo)入Icon

3、創(chuàng)建Unity的CustomFont

3.1 BMFontTool

??先給出工具的完整代碼,要說明的點(diǎn)后面慢慢寫。

public class BMFontTool
{
    public static Regex BMCharMatch =
        new Regex(
            @"char id=(?<id>\d+)\s+x=(?<x>\d+)\s+y=(?<y>\d+)\s+width=(?<width>\d+)\s+height=(?<height>\d+)\s+xoffset=(?<xoffset>\d+)\s+yoffset=(?<yoffset>\d+)\s+xadvance=(?<xadvance>\d+)\s+");

    public static Regex BMInfoMatch =
        new Regex(@"common lineHeight=(?<lineHeight>\d+)\s+.*scaleW=(?<scaleW>\d+)\s+scaleH=(?<scaleH>\d+)");

    public const string BMFontExt = ".fnt";
    public const string FontExt = ".fontsettings";

    public static string GetConfPath()
    {
        Object obj = Selection.activeObject;
        string cfgPath = AssetDatabase.GetAssetPath(obj);
        if (!cfgPath.EndsWith(".fnt"))
        {
            Debug.LogError("請選擇.fnt文件??!");
            return null;
        }
        return cfgPath;
    }

    [MenuItem("Assets/Create Font")]
    public static void CreateFromBMFont()
    {
        string cfgPath = GetConfPath();
        if (null == cfgPath) return;

        string name = Path.GetFileNameWithoutExtension(cfgPath);
        int lineHeight = 1;
        // 創(chuàng)建材質(zhì)
        Material mat = new Material(Shader.Find("UI/Unlit/Text Detail"))
        {
            name = name,
            mainTexture = AssetDatabase.LoadAssetAtPath<Texture>(cfgPath.Replace(BMFontExt, ".png")),
        };
        mat.SetTexture("_DetailTex", mat.mainTexture);
        // 創(chuàng)建字體
        Font customFont = new Font(name)
        {
            material = mat,
            characterInfo = ParseBMFont(cfgPath, ref lineHeight).ToArray(),
        };
        // 修改行高
        SerializedObject serializedFont = new SerializedObject(customFont);
        SetLineHeight(serializedFont, lineHeight);
        serializedFont.ApplyModifiedProperties();
        // 保存
        AssetDatabase.CreateAsset(mat, cfgPath.Replace(BMFontExt, ".mat"));
        AssetDatabase.CreateAsset(customFont, cfgPath.Replace(BMFontExt, FontExt));
    }

    [MenuItem("Assets/Build Font")]
    public static void BuildFromBMFont()
    {
        string cfgPath = GetConfPath();
        if (null == cfgPath) return;

        string fontPath = cfgPath.Replace(BMFontExt, FontExt);
        if (!File.Exists(fontPath)) return;

        Font customFont = AssetDatabase.LoadAssetAtPath<Font>(fontPath);
        int lineHeight = 1;
        List<CharacterInfo> chars = ParseBMFont(cfgPath, ref lineHeight);
        SerializeFont(customFont, chars, lineHeight);
        Debug.Log("字體更新完成", customFont);
    }

    public static List<CharacterInfo> ParseBMFont(string path, ref int lineHeight)
    {
        List<CharacterInfo> chars = new List<CharacterInfo>();
        using (StreamReader reader = new StreamReader(path))
        {
            // 文字貼圖的寬、高
            float texWidth = 1;
            float texHeight = 1;

            string line = reader.ReadLine();
            while (line != null)
            {
                if (line.StartsWith("char id="))
                {
                    Match match = BMCharMatch.Match(line);
                    if (match != Match.Empty)
                    {
                        int id = Convert.ToInt32(match.Groups["id"].Value);
                        int x = Convert.ToInt32(match.Groups["x"].Value);
                        int y = Convert.ToInt32(match.Groups["y"].Value);
                        int width = Convert.ToInt32(match.Groups["width"].Value);
                        int height = Convert.ToInt32(match.Groups["height"].Value);
                        int xoffset = Convert.ToInt32(match.Groups["xoffset"].Value);
                        int yoffset = Convert.ToInt32(match.Groups["yoffset"].Value);
                        int xadvance = Convert.ToInt32(match.Groups["xadvance"].Value);
                        // 轉(zhuǎn)換為Unity UV坐標(biāo)
                        float uvMinX = x / texWidth;
                        float uvMaxX = (x + width) / texWidth;
                        float uvMaxY = 1 - (y / texHeight);
                        float uvMinY = (texHeight - height - y) / texHeight;

                        // Unity字體UV的是 [左下(0, 0) - 右上(1, 1)]
                        // BMFont的UV是 [左上(0,0) - 右下(1, 1)]
                        CharacterInfo info = new CharacterInfo
                        {
                            // 字符的Unicode值
                            index = id,
                            uvBottomLeft = new Vector2(uvMinX, uvMinY),
                            uvBottomRight = new Vector2(uvMaxX, uvMinY),
                            uvTopLeft = new Vector2(uvMinX, uvMaxY),
                            uvTopRight = new Vector2(uvMaxX, uvMaxY),
                            minX = xoffset,
                            minY = -height / 2, // 居中對齊
                            glyphWidth = width,
                            glyphHeight = height,
                            // The horizontal distance from the origin of this character to the origin of the next character.
                            advance = xadvance,
                        };
                        chars.Add(info);
                    }
                }
                else if (line.IndexOf("scaleW=", StringComparison.Ordinal) != -1)
                {
                    Match match = BMInfoMatch.Match(line);
                    if (match != Match.Empty)
                    {
                        lineHeight = Convert.ToInt32(match.Groups["lineHeight"].Value);
                        texWidth = Convert.ToInt32(match.Groups["scaleW"].Value);
                        texHeight = Convert.ToInt32(match.Groups["scaleH"].Value);
                    }
                }
                line = reader.ReadLine();
            }
        }
        return chars;
    }

    public static void SetLineHeight(SerializedObject font, float height)
    {
        font.FindProperty("m_LineSpacing").floatValue = height;
    }

    /// <summary>
    /// 序列化自定義字體
    /// </summary>
    /// <param name="font">字體資源</param>
    /// <param name="chars">全部字符信息</param>
    /// <param name="lineHeight">顯示的行高</param>
    public static SerializedObject SerializeFont(Font font, List<CharacterInfo> chars, float lineHeight)
    {
        SerializedObject serializedFont = new SerializedObject(font);
        SetLineHeight(serializedFont, lineHeight);
        SerializeFontCharInfos(serializedFont, chars);
        serializedFont.ApplyModifiedProperties();
        return serializedFont;
    }

    /// <summary>
    /// 序列化字體中的全部字符信息
    /// </summary>
    public static void SerializeFontCharInfos(SerializedObject font, List<CharacterInfo> chars)
    {
        SerializedProperty charRects = font.FindProperty("m_CharacterRects");
        charRects.arraySize = chars.Count;
        for (int i = 0; i < chars.Count; ++i)
        {
            CharacterInfo info = chars[i];
            SerializedProperty prop = charRects.GetArrayElementAtIndex(i);
            SerializeCharInfo(prop, info);
        }
    }

    /// <summary>
    /// 序列化一個(gè)字符信息
    /// </summary>
    public static void SerializeCharInfo(SerializedProperty prop, CharacterInfo charInfo)
    {
        prop.FindPropertyRelative("index").intValue = charInfo.index;
        prop.FindPropertyRelative("uv").rectValue = charInfo.uv;
        prop.FindPropertyRelative("vert").rectValue = charInfo.vert;
        prop.FindPropertyRelative("advance").floatValue = charInfo.advance;
        prop.FindPropertyRelative("flipped").boolValue = false;
    }
}

3.2 細(xì)節(jié)說明

??上面代碼的核心部分,來自于參考文章,當(dāng)然也有自己的補(bǔ)充和修改內(nèi)容。

3.2.1 解決代碼生成的CustomFont信息會丟失問題

??參考文章實(shí)現(xiàn)了創(chuàng)建CustomFont的功能,但是需要手動保存(Ctrl+S),否則在關(guān)閉Unity或切換場景后,字體中的信息就丟失了。
  丟失的原因是,直接修改Load出來的Font對象,并不會將修改的內(nèi)容序列化保存。這里我使用SerializedObject對字體進(jìn)行修改,它可以通過ApplyModifiedProperties更新序列化的內(nèi)容。
  另外代碼中使用new Font() + AssetDatabase.CreateAsset()也可以保留序列化信息,但它只能用在創(chuàng)建字體時(shí)。更新字體用它會刪掉舊字體,并創(chuàng)建一個(gè)新的,那么項(xiàng)目中用到舊字體的地方就會Missing。

3.2.2 文字無法換行

換行錯(cuò)亂

??上圖的現(xiàn)象是沒有設(shè)置行高導(dǎo)致的。Inspector中行高的參數(shù)是Line Spacing,而在代碼中是Font.lineHeight。這里需要注意lineHeight是只讀屬性,想在代碼里設(shè)置行高,只能借助SerializedObject。

3.2.3 豎直方向上的文字對齊

??代碼中保證了豎直居中對齊是正確的,但是上對齊、下對齊的位置會出現(xiàn)問題。我探索出了在三種對齊方式下分別正確的參數(shù),但是不能同時(shí)滿足三種對齊 Orz...

minY或maxY只需要設(shè)置一個(gè)即可

  • 上對齊?。?minY = -height/2 - yoffset*2
  • 居中對齊: minY = -height / 2
  • 下對齊?。?maxY = height-yoffset

??雖然從參數(shù)上不能同時(shí)適配三種對齊,但勾選Text組件的Align By Geometry選項(xiàng)可以解決問題。
  如果有朋友解決了這個(gè)問題,請不吝賜教。還有minX、minY、maxX、maxY這幾個(gè)參數(shù)的含義我也沒搞懂,文檔的信息實(shí)在是不清不楚 ……了解的朋友也請留言。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容