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).
The easiest way to do this, is to use the TextButton class from libgdx. The text from a TextButton is centered by default. This still works!
It's free and royalty-free, which is good unlike Unity, and it's on Java so it's relatively fast.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With