Search code examples
javaandroidlibgdxlabelbitmap-fonts

Libgdx text on Android


I'm new to libgdx and i'm trying to display some text on the screen.

I've watched several tutorials, and they're all saying that I should initiate the BitmapFont with no parameters and it will then use the default font. But on my android device it just shows these black rectangles: Black rectangles in shape of the letters

And here's my code:

public class GameOverScreen implements Screen {
    private JumpGame game;
    private OrthographicCamera cam;

    private BitmapFont gameOverFont;
    private Label.LabelStyle labelStyle;
    private Label label;

public GameOverScreen(JumpGame game) {
    this.game = game;
    cam = new OrthographicCamera();

    gameOverFont = new BitmapFont();
    labelStyle = new Label.LabelStyle(gameOverFont, Color.BLACK);
    label = new Label("Game Over", labelStyle);
}

@Override
public void show() {
    cam.setToOrtho(false, game.getWidth() / 4, game.getHeight() / 4);
    game.batch.setProjectionMatrix(cam.combined);
}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    game.batch.begin();
    label.draw(game.batch, 1);
    game.batch.end();
}

@Override
public void resize(int width, int height) {

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {

}
}

EDIT:

Okay so I was launching the Screen with the text from a second thread. When I launch it "normally" it works fine. Can someone explain why this is, and how to work around it if I want to still launch it from the thread?


Solution

  • According to the wiki

    To pass data to the rendering thread from another thread we recommend using Application.postRunnable(). This will run the code in the Runnable in the rendering thread in the next frame, before ApplicationListener.render() is called.


    Label is part of libgdx's 2D scene graph so it's better to use with Stage.

    If you want to draw font you can simply draw with the help of Batch.

    font.draw(batch,"Hello World",100,100);