unity將圖片轉(zhuǎn)換成字體的方法
本文實(shí)例為大家分享了unity利用圖片來生成字體的具體代碼,供大家參考,具體內(nèi)容如下
開發(fā)中,可能會用到需要將圖片轉(zhuǎn)換成字體的需求。
BMFONT 插件 導(dǎo)入圖片


然后生成 .fnt 和 .png 兩個文件 (文件格式可以在設(shè)置中更改)
將這兩個文件導(dǎo)入unity 將png 切割成精靈
創(chuàng)建材質(zhì)、將貼圖拖上去。
創(chuàng)建字體、將材質(zhì)拖上去。

數(shù)據(jù)怎么算出來的公式百度上面有,此處略去。也可以利用代碼來生成
using UnityEngine;
using System.Collections;
using System;
using System.Xml;
public class CustomFontImportor : MonoBehaviour {
public Font font;
public TextAsset textAsset;
void Awake()
{
if (font == null || textAsset == null)
{
Debug.LogError("請設(shè)置font和textAsset.");
return;
}
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(textAsset.text);
int totalWidth = Convert.ToInt32(xmlDocument["font"]["common"].Attributes["scaleW"].InnerText);
int totalHeight = Convert.ToInt32(xmlDocument["font"]["common"].Attributes["scaleH"].InnerText);
XmlElement xml = xmlDocument["font"]["chars"];
ArrayList characterInfoList = new ArrayList();
for (int i = 0; i < xml.ChildNodes.Count; ++i)
{
XmlNode node = xml.ChildNodes[i];
if (node.Attributes == null)
{
continue;
}
int index = Convert.ToInt32(node.Attributes["id"].InnerText);
int x = Convert.ToInt32(node.Attributes["x"].InnerText);
int y = Convert.ToInt32(node.Attributes["y"].InnerText);
int width = Convert.ToInt32(node.Attributes["width"].InnerText);
int height = Convert.ToInt32(node.Attributes["height"].InnerText);
int xOffset = Convert.ToInt32(node.Attributes["xoffset"].InnerText);
int yOffset = Convert.ToInt32(node.Attributes["yoffset"].InnerText);
int xAdvance = Convert.ToInt32(node.Attributes["xadvance"].InnerText);
CharacterInfo info = new CharacterInfo();
Rect uv = new Rect();
uv.x = (float)x / totalWidth;
uv.y = (float)(totalHeight - y - height) / totalHeight;
uv.width = (float)width / totalWidth;
uv.height = (float)height / totalHeight;
info.index = index;
info.uvBottomLeft = new Vector2(uv.xMin, uv.yMin);
info.uvBottomRight = new Vector2(uv.xMax, uv.yMin);
info.uvTopLeft = new Vector2(uv.xMin, uv.yMax);
info.uvTopRight = new Vector2(uv.xMax, uv.yMax);
info.minX = xOffset;
info.maxX = xOffset + width;
info.minY = -yOffset - height;
info.maxY = -yOffset;
info.advance = xAdvance;
info.glyphWidth = width;
info.glyphHeight = height;
characterInfoList.Add(info);
}
font.characterInfo = characterInfoList.ToArray(typeof(CharacterInfo)) as CharacterInfo[];
Debug.Log("生成成功.");
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
.Net(c#)漢字和Unicode編碼互相轉(zhuǎn)換實(shí)例
下面小編就為大家?guī)硪黄?Net(c#)漢字和Unicode編碼互相轉(zhuǎn)換實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
WPF利用CommunityToolkit.Mvvm實(shí)現(xiàn)級聯(lián)選擇器
這篇文章主要介紹了WPF如何利用CommunityToolkit.Mvvm實(shí)現(xiàn)級聯(lián)選擇器,文中的示例代碼講解詳細(xì),對我們的學(xué)習(xí)或工作有一定幫助,需要的小伙伴可以參考一下2023-12-12

