Dakota
Dakota

Reputation: 125

LibGDX - how do I make my text centered?

I'm new to LibGDX and I am taking it slowly. I'm still trying to understand most things which is why typically google searches don't help due to the fact that their too complicated. I have a main menu that has text that I want centered no matter what the screen size is. Here is the code that I have for that menu.

public class Menu implements Screen {

SlingshotSteve game;

OrthographicCamera camera;

public Menu(final SlingshotSteve gam) {
    this.game = gam;

    camera = new OrthographicCamera();
    camera.setToOrtho(false, 800, 480);
}

@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0, 0, 0.2f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    camera.update();
    game.batch.setProjectionMatrix(camera.combined);

    game.batch.begin();
    game.font.draw(game.batch, "Welcome to Slingshot Steve!!! ", 100, 150);
    game.font.draw(game.batch, "Tap anywhere to begin!", 100, 100);
    game.batch.end();

    if (Gdx.input.isTouched()) {
        game.setScreen((Screen) new GameScreen(game));
        dispose();
    }
}

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

}

@Override
public void show() {

}

@Override
public void hide() {

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void dispose() {

}

}

Upvotes: 0

Views: 536

Answers (2)

noone
noone

Reputation: 19776

It is possible to do it the way Nine Magics suggested, however one would usually do it via a Stage, which is part of scene2d.

More specifically one would use scene2d.ui which is a bunch of Actors like Button, Image, Label etc. You can attach a ClickListener to a Button for example and react on this event.

Furthermore, for layouting there is one very powerful Actor, namely Table which you can very easily use to center things on the screen.

Some very minimalistic code:

// do this once, in create() or show()
Skin skin = new Skin("uiskin.json"); // get the demo skin from the libgdx test resources
Stage stage = new Stage();
Table table = new Table(skin);
table.add("Welcome to Slingshot Steve!!!");
table.row();
table.add("Tap anywhere to begin!");
stage.addActor(table);

// do this in your render loop
stage.act();
stage.draw();

You can find the "default" skin resources here. You need to get all the uiskin.* files.

Upvotes: 1

Nine Magics
Nine Magics

Reputation: 444

I'm here to save you!

To get width / height from a String drawn with your BitmapFont you can utilize this super nice method:

game.font.getBounds(String string)

And to use it in your case, it would be something like this:

game.font.getBounds("Tap anywhere to begin!").width / 2;

Cheers!

Upvotes: 1

Related Questions