How to create LibGDX Buttons from nine patch

Tue, 08 Mar 2016

Check out Lines Galaxy Android game to view the results in action.

One of the most promising frameworks for creating 2D graphics in Android (and Web, iOS, Windows) is LibGDX.

Drawing complex buttons in 2D graphics is not exactly easy. One option would be to convert your button design into nine patch images and use them in your Android apps.

The bellow class is missing some crucial methods. Bare in mind that only the code required for drawing the buttons in LibGDX is posted here. Copy-pasting the whole class might not work.

Here's how you can create LibGDX Buttons which use nine patch image packs (the bellow code creates a single button):

// you'll manage the imports public class MyClass extends ApplicationAdapter {

private TextureAtlas buttonAtlas;
private NinePatch buttonNinePatch;
private TextButton textButton;
private SpriteBatch batch;

@Override
public void create () {

    batch = new SpriteBatch();

    buttonAtlas = new TextureAtlas("buttons.pack");
    buttonNinePatch= buttonAtlas.createPatch("button1");
    NinePatchDrawable ninePatchDrawable = new NinePatchDrawable(buttonNinePatch);
    TextButtonStyle textButtonStyle = new TextButtonStyle();

    // you might want to use different nine patch for each button state
    textButtonStyle.up = ninePatchDrawable;
    textButtonStyle.down = ninePatchDrawable;
    textButtonStyle.checked = ninePatchDrawable;
    textButtonStyle.over = ninePatchDrawable;

    textButtonStyle.font = new BitmapFont();

    // LibGDX Buttons
    textButton = new TextButton("My Button", textButtonStyle);
    textButton.setPosition(0, 0);
    textButton.setSize(200, 200);

}

@Override
public void render () {

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

    batch.begin();
    textButton.draw(batch, 1f);
    batch.end();

}

}

That's all.
Now (as President Francis says in House of Cards) "no one said" 2D graphics in Android "will be easy".

After you'll run the above code you'll see that there's a problem. The font is not exactly as you'd expected. Well you could scale it but it won't output the expected result and it will actually be pixelated. This is where FreeTypeFontGenerator jumps in.

The next post will cover how to use them in your Android LibGDX app.

Check this post in case you're not familiar to how buttons.pack works and where it comes from.

Check out Lines Galaxy Android game to view the results in action.

Categories: android, libgdx