1.首先我們需要把位圖字體導(dǎo)入到unity中,然后利用插件轉(zhuǎn)化一下 我使用的是BMFont
2.然后我們就可以看到生成了四個(gè)文件,其中我們主要注意的是.fontsettings文件,
我們主要修改的就是?Character Rect里面的各個(gè)參數(shù),至于具體是什么 ,大家有興趣的可以去搜索,
好了 我們直接上代碼
把腳本掛載到text組件上面
其中singleFontWidth和singleFontHeight是你當(dāng)前位圖字體的參數(shù)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class BitmapFontResizer : MonoBehaviour
{? ? public float singleFontWidth = 65;//單個(gè)位圖字體的寬度
? ? public float singleFontHeight = 90;//單個(gè)位圖字體的高度
? ? private Text textComponent;//text組件
? ? private float maxLenth = 580;//text框的長(zhǎng)度
? ? public Font myFont;
? ? void Start()
? ? {
? ? ? ? myFont = Instantiate(myFont);//實(shí)例化一個(gè)字體,不然會(huì)修改源文件參數(shù)
? ? ? ? textComponent = GetComponent<Text>();
? ? ? ? textComponent.font = myFont;
? ? ? ? CharacterInfo[] _characterInfo = textComponent.font.characterInfo;
? ? ? ? if (textComponent.text.Length * singleFontWidth >= maxLenth)
? ? ? ? {
? ? ? ? ? ? float coefficient = maxLenth / (textComponent.text.Length * singleFontWidth);//計(jì)算比例系數(shù)
? ? ? ? ? ? for (int i = 0; i < _characterInfo.Length; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? _characterInfo[i].glyphWidth = (int)(_characterInfo[i].glyphWidth * coefficient);//修改寬度
? ? ? ? ? ? ? ? //_characterInfo[i].glyphHeight = (int)(_characterInfo[i].glyphHeight * coefficient);//修改高度,(這個(gè)會(huì)同時(shí)修改Vert里面的Y,與預(yù)先的不適合,謹(jǐn)慎使用)
? ? ? ? ? ? ? ? _characterInfo[i].advance = (int)(_characterInfo[i].advance * coefficient);//寬度發(fā)生變化后需要修改字體之間的間隔
? ? ? ? ? ? ? ? _characterInfo[i].vert.height = (int)(_characterInfo[i].vert.height * coefficient);//棄用的,但是還可以使用我用的是unity2021,單純修改高度
? ? ? ? ? ? ? ? _characterInfo[i].vert.y = (int)(_characterInfo[i].vert.y * coefficient);//棄用的,但是還可以使用我用的是unity2021,修改Y值
? ? ? ? ? ? }文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-751767.html? ? ? ? }
? ? ? ? textComponent.font.characterInfo = _characterInfo;//對(duì)characterInfo進(jìn)行賦值
? ? }
}文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-751767.html
到了這里,關(guān)于Unity UGUI使用Text組件位圖字體進(jìn)行自適應(yīng)大小的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!