我在谷歌上搜索如何使用 Libgdx 绘制简单的 2D 文本时遇到了很多麻烦.以下是我目前整理的代码:
I've been having a lot of trouble Googling how to draw simple 2D text with Libgdx. Here is the code that I've put together so far:
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()
几乎每个语句子集.
The code does draw the Hello World string, however, it messes up all my other drawings. They are there, only brutally mutilated, and move and all that. I've tried Gdx.gl11.glPushMatrix()
and Gdx.gl11.glPopMatrix()
around just about every subset of statements.
我已将残缺的绘图缩小到 font.draw()
调用,如果将其取出,一切正常(但当然没有文字).
I've narrowed the mutilated drawings down to the font.draw()
call, if that's taken out, everything works fine (but of course there is no text then).
我没有看到为文本绘制创建单独批处理的太多理由.使用 gdxVersion = '1.4.1'(在 Android Studio 中使用 gradle 构建)代码成功绘制文本:
I don't see much reason of creating separate batch for text drawing. Using gdxVersion = '1.4.1' (built with gradle in Android Studio) that code draws text successfully:
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/
Note, that here you draw in game world coordinates, so if your character moves (in platformer, for example), than text will move too. If you want to see text, that it will be fixed on screen, something like Label/TextField or how it is called in different UI frameworks, than I recommend to use Stage (and TextArea for text), see for example on how to use Stage here: http://www.toxsickproductions.com/libgdx/libgdx-basics-create-a-simple-menu/
这篇关于如何使用 Libgdx/Java 绘制文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!