Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 遊戲 >> Android 遊戲開發

Android遊戲引擎libgdx使用教學3:繪製漢字與顯示中文

編輯:Android 遊戲開發

不知大家有沒有注意過 libgdx 顯示漢字的問題?其實這非常值得關注,試想如果 libgdx 不支援中文,使用起來就很不方便了。

我們來看看 BitmapFont 類別,這是與文字繪製相關的。看一下原始碼:

public BitmapFont () {
    this(Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.fnt"),
        Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.png"),
        false, true);
}

這是預設的建構方法,可以看出它載入了兩個檔案:arial-15.fnt 和 arial-15.png。

arial-15.fnt 的部分內容:

info face="Arial" size=15 bold=0 italic=0 charset="" unicode=0
     stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1
common lineHeight=18 base=14 scaleW=256 scaleH=256 pages=1 packed=0
page id=0 file="arial-15.png"
chars count=189
char id=32  x=0 y=0 width=0 height=0 xoffset=0 yoffset=14 xadvance=4 page=0 chnl=0
char id=255 x=0 y=0 width=8 height=19 xoffset=-1 yoffset=0 xadvance=7 page=0 chnl=0
...
kernings count=374
kerning first=49 second=49 amount=-1
kerning first=121 second=44 amount=-1
...

再看看 arial-15.png:

可以明顯看出,libgdx 的文字繪製,是根據 fnt 檔取得對應文字在 png 中的座標位置,然後截取圖片的相應部分來繪製。

那麼要讓 libgdx 支援中文,思路就很簡單了:我們自己建立 fnt 與 png 檔,其中包含我們要使用的中文即可。

作者提供了一個對應的工具:Hiero。下載後雙擊運行,在右側列表中選擇一個可用的字型,然後輸入需要的中文(最好保留自動產生的英文和符號)。

在右側的 Effects 中可以設定效果:

點 File — Save as BMFont Files 產生兩個檔案,把它們複製到 assets 資料夾。

使用時:

bitmapFont = new BitmapFont(Gdx.files.internal("cf.fnt"),
    Gdx.files.internal("cf.png"), false);

指定我們產生的檔案作為繪製參考,然後繪製:

bitmapFont.draw(spriteBatch, "FPS" + Gdx.graphics.getFramesPerSecond(),
    5, Gdx.graphics.getHeight() - 10);
bitmapFont.draw(spriteBatch, "祝大家光棍節快樂",
    0, Gdx.graphics.getHeight() / 2 - 8);

程式運行效果:

關於多行文字,可以呼叫

public TextBounds drawMultiLine (SpriteBatch spriteBatch, CharSequence str,
    float x, float y)

或者

public TextBounds drawMultiLine (SpriteBatch spriteBatch, CharSequence str,
    float x, float y, float alignmentWidth, HAlignment alignment)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved