Android Libgdx 显示文字

1,855 阅读1分钟

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

后面就是正常的步骤