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();
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.
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).
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();
}
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/