我在谷歌上搜索如何使用 Libgdx 绘制简单的 2D 文本时遇到了很多麻烦。以下是我目前整理的代码:
SpriteBatch spriteBatch;
BitmapFont font;
CharSequence str = "Hello World!";
spriteBatch = new SpriteBatch();
font = new BitmapFont();
spriteBatch.begin();
font.draw(spriteBatch, str, 10, 10);
spriteBatch.end();
代码确实绘制了 Hello World 字符串,但是,它弄乱了我所有的其他绘图。他们在那里,只是被残忍地肢解,移动等等。我已经尝试了 Gdx.gl11.glPushMatrix()
和 Gdx.gl11.glPopMatrix()
几乎每个语句子集。
我已将残缺的绘图缩小到 font.draw()
调用,如果将其取出,一切正常(但当然没有文字)。
最佳答案
我认为没有太多理由为文本绘图创建单独的批处理。使用 gdxVersion = '1.4.1'(在 Android Studio 中使用 gradle 构建)代码成功绘制文本:
BitmapFont font = new BitmapFont(); //or use alex answer to use custom font
public void render( float dt )
{
batch.setProjectionMatrix(camera.combined); //or your matrix to draw GAME WORLD, not UI
batch.begin();
//draw background, objects, etc.
for( View view: views )
{
view.draw(batch, dt);
}
font.draw(batch, "Hello World!", 10, 10);
batch.end();
}
注意,这里你绘制的是游戏世界坐标,所以如果你的角色移动(例如在平台游戏中),文本也会移动。如果您想查看文本,它将被固定在屏幕上,例如 Label/TextField 或如何在不同的 UI 框架中调用它,而不是我建议使用 Stage(和 TextArea 用于文本),例如如何使用这里的舞台:http://www.toxsickproductions.com/libgdx/libgdx-basics-create-a-simple-menu/
关于java - 如何使用 Libgdx/Java 绘制文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12466385/