一、首先是共有的步骤
使用工具 : BMFont
下载地址:http://www.angelcode.com/products/bmfont/
因为测试版的不稳定性,这里下载1.13版即可
打开BMFont,Edit–>Open Image Manager–>Image–>Import image…选中图片后将Id设为图片所示数字的ASCII码,这里我设置了0-9的数字
结果如图
然后Options–>Export Options
再点击Options–>Save bitmap font as…会生成.fnt和.png两个文件,导入Unity项目中
二、如果在NGUI中使用
右击.fnt文件–>NGUI–>Open Bitmap Font Maker,将Type设为Imported Bitmap,拖入相应的.fnt文件和.png文件并设置图集,会生成一个Prefab文件即NGUI可使用的字体。注意使用时字体大小要设为Snap
三、如果在UGUI中使用
因为UGUI中没有对应的功能,这里就需要自己编写代码
具体步骤:
1. 将.png文件设为sprite
2. 创建一个材质球,shader设为GUI/Text Shader
3. 右击–>Create–>Custom Font
4. 把材质球拖入字体材质中
5. 导入所需要的NGUI的5个脚本
6. 编写脚本
using UnityEditor;
public class BMFontEditor : EditorWindow {
[MenuItem("Tools/BMFont Maker")]
static public void OpenBMFontMaker()
{EditorWindow.GetWindow<BMFontEditor>(false, "BMFont Maker", true).Show();
}[SerializeField]
private Font targetFont;
[SerializeField]
private TextAsset fontData;
[SerializeField]
private Material fontMat;
[SerializeField]
private Texture2D fontTexture;private BMFont bmFont = new BMFont();public BMFontEditor() {
}private void OnGUI()
{targetFont = EditorGUILayout.ObjectField("Target Font", targetFont, typeof(Font), false) as Font;fontData = EditorGUILayout.ObjectField("Font Data", fontData, typeof(TextAsset), false) as TextAsset;fontMat = EditorGUILayout.ObjectField("Font Mat", fontMat, typeof(Material), false) as Material;fontTexture = EditorGUILayout.ObjectField("Font Texture", fontTexture, typeof(Texture2D), false) as Texture2D;if (GUILayout.Button("Create BMFont")){BMFontReader.Load(bmFont, fontData.name, fontData.bytes);CharacterInfo[] characterInfo = new CharacterInfo[bmFont.glyphs.Count];for (int i = 0; i < bmFont.glyphs.Count; i++){BMGlyph bmInfo = bmFont.glyphs[i];CharacterInfo info = new CharacterInfo();info.index = bmInfo.index;info.uv.x = (float)bmInfo.x / (float)bmFont.texWidth;info.uv.y = 1 - (float)bmInfo.y / (float)bmFont.texHeight;info.uv.width = (float)bmInfo.width / (float)bmFont.texWidth;info.uv.height = -1f*(float)bmInfo.height / (float)bmFont.texHeight;info.vert.x = 0;info.vert.y = -(float)bmInfo.height;info.vert.width = (float)bmInfo.width;info.vert.height = (float)bmInfo.height;info.width = (float)bmInfo.advance;characterInfo[i] = info;}targetFont.characterInfo = characterInfo;if (fontMat){fontMat.mainTexture = fontTexture;}targetFont.material = fontMat;fontMat.shader = Shader.Find("UI/Default");AssetDatabase.SaveAssets();Close();}}
7. Tools–>BMFont Maker
注意使用时Text的Material可设为Sprites-Default
最后效果如图