1. 程式人生 > >Android Libgdx 顯示文字

Android Libgdx 顯示文字

Libgdx有兩種顯示文字的方式:

第一種:

通過貼圖的方式顯示,使用BitmapFont和SpriteBatch組合來完成文字的繪製,構造BitmapFont時需要一個描述文字構成的fnt檔案,和一個提供文字圖片的png檔案。具體的可以看看這個教程

另一種:

直接使用ttf檔案,就是FreeType方式。這裡有個教程。但是這個教程的版本比較舊了,新版的libgdx1.9.8版本是使用gradle方式整合。具體的api也與上面的教程有所變化。變化後的使用方式如下。

首先,在專案的build.gradle檔案中引入:

……
ext {
        ……
        gdxVersion = '1.9.8'
…… } project(":android") { apply plugin: "android" apply plugin: "kotlin-android" configurations { natives } dependencies { compile project(":core") compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion
:natives-armeabi"
natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-arm64-v8a" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion
:natives-x86_64"
compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion" …… natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi" natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi-v7a" natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-arm64-v8a" natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86" natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86_64" compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" } } project(":core") { apply plugin: "kotlin" dependencies { compile "com.badlogicgames.gdx:gdx:$gdxVersion" compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion" …… compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" } } 複製程式碼

然後寫程式碼:

        private var font: BitmapFont? = null
        private var generator: FreeTypeFontGenerator? = null
    
        var freeTypeFontParameter = FreeTypeFontGenerator.FreeTypeFontParameter()
        freeTypeFontParameter.color = Color.BLACK
        freeTypeFontParameter.size = 40
        ……//還有一些其他的屬性可以設定
        freeTypeFontParameter.characters = DEFAULT_CHARS + "你需要的文字,不能重複,都寫在這裡"
        font = generator!!.generateFont(freeTypeFontParameter)



        style.font = font
複製程式碼

後面就是正常的步驟