Search code examples
libgdxnine-patchtexture-atlas

Libgdx packing a NinePatch into TextureAtlas


I have seen, that you can pack NinePatches into TextureAtlas by using TexturePacker2. I have also seen this and this. But i am not sure if understood it correct. I want to pack all my GUI-stuff into one TextureAtlas and my GUI-stuff is not only made of NinePatchs but also of some TextureRegions. Is it possible to combine NinePatchs and TextureRegions in one TextureAtlas? Can i use the deffault settings or do i have to make some custom settings like paddingX, paddingY in the .JSON file? And in my game can i load the NinePatch by using atlas.createPatch("patchimagename"); or would it be better to safe everything as TextureRegions and create the NinePatch out of it?


Solution

  • Lets imagine you have that files structure you use for TexturePacker2:

    images/
      image1.png
      image2-ninepatch.png   <-- this is NinePatch
      image3.png
    

    Just change your extention of NinePatch files from .png (for example) to .9.png (and add 1px border to it, if needed).

    images/
      ...
      image2-ninepatch.9.png
      ...
    

    After this you could use Skin to wrap your textures and easly extract NinePatch and TextureRegion from Atlas:

    TextureAtlas atlas = ... // load the Atlas
    Skin skin = ... // create some root skin or use created one
    skin.addRegion(atlas); // register atlas in skin
    

    Furthermore, you could add many atlases to one skin!

    Now you could do these:

    1. Get TextureRegion by name:

      public TextureRegion getRegion(String region)
      {
          return skin.getRegion(region);
      }
      
    2. Get NinePatch by name:

      public NinePatch getNinePatch(String region)
      {
          return skin.getPatch(region);
      }
      
    3. Even use your images (TextureRegion or NinePatch) in your UI components (like button background etc) that use this skin.

    I hope it helps you!