Search code examples
javalibgdxnine-patch

Combining TextureRegions for Button backgrounds


I want to piece together multiple TextureRegions or Sprites. I have a custom button creation method that works using standard Java2D and I'd like to implement it in a LibGDX project. Basically, I have my standard button background which I split into 9 different parts. The corners, the borders (discluding the corners) on the sides, and the center. Then I resize the center to fit the text and then I resize the borders to fit the center's new width and height, and finally I reattach the corners. Now this again all works in Java2D, but I'm having difficulties getting it to work in LibGDX. The splitting works and I can resize by converting the center to a Sprite and set the size to the text's bounds, however the difficulty I'm encountering is reassembling the individual TextureRegions.

Is what I want to do possible, and if so, how? Or, will I have to create all button images using an external program like Gimp and then importing them separately (which is much more inflexible)?


Solution

  • Libgdx use a NinePatch image (a concept it got from Android -- presumably it predates Android, but I'm not sure) for scalable button textures.

    The idea is that you have a single texture and define which parts are the non-scalable corners, and the rest is scaled for you.

    Libgdx's implementation assumes the texture atlas you're using has encoded the 9-patch metadata, but you should be able to use the NinePatch constructor directly if you already know how much of the button is border.