---
title: "libgdx学习之TexturePacker"
author: "macken"
date: "2013-03-14T19:30:55Z"
tags: ["Android", "Libgdx", "Mobile", "game"]
categories: ["移动开发"]
slug: "libgdx-texturepacker"
draft: false
lastmod: "2013-03-14T19:31:17Z"
id: 1829561
url: "https://macken.iteye.com/blog/1829561"
---

由于android手机计算资源有限，cpu、gpu的时候都十分宝贵，因此游戏中用到的图片分成单个进行加载以及渲染是一件非常浪费资源的事情，因此需要将多个小图片合并到一个大图片中，达到一次加载多次使用的目的，这个合并原理与web页面设计中合并图片的道理类似，但是手工合并这些文件显然是一件很痛苦的事情，尤其后期需要改动的时候简直是灾难了。

       libgdx提供了一个很好的工具来解决这个问题TexturePacker，如果在使用最新版libgdx时会看到两个，一个是TexturePacker，一个是TexturePacker2，第一个已经被弃用，现在使用的是TexturePacker2，两者的区别可以见[http://www.badlogicgames.com/wordpress/?p=2495](http://www.badlogicgames.com/wordpress/?p=2495)

TexturePacker2的使用非常方便，代码示例

```
public static void main(String[] args){
		Settings settings=new Settings();
		settings.alias=true;
		settings.flattenPaths=true;
		TexturePacker2.process(settings, "D:\\img", "D:\\img\\output","macken.pack");
}
```

方法定义

```
static public void process (Settings settings, String input, String output, String packFileName)；
```

 

 运行过程

扫描input文件下的图片合并成一个文件，默认情况下会将一个文件下的图片合并成一个图片大文件，默认图片的size是1024\*1024，超过大小会分成两个图片，可以通过修改settings的属性设定合并过程以及输出的文件属性，settings的常用属性

```
{
        pot: true,
        paddingX: 2,
        paddingY: 2,
        duplicatePadding: true,
        edgePadding: true,
        rotation: false,
        minWidth: 16,
        minHeight: 16,
        maxWidth: 1024,
        maxHeight: 1024,
        stripWhitespaceX: false,
        stripWhitespaceY: false,
        alphaThreshold: 0,
        filterMin: Nearest,
        filterMag: Nearest,
        wrapX: ClampToEdge,
        wrapY: ClampToEdge,
        format: RGBA8888,
        alias: true,
        outputFormat: png,
        jpegQuality: 0.9,
        ignoreBlankImages: true,
        fast: false,
        debug: false,
        combineSubdirectories: false,
        jsonOutput: true,
        flattenPaths: false
}
```

 

TextureAtlas

对于TexturePacker合成的图片，使用TextureAtlas读取，读取代码示例

```
TextureAtlas atlas=new TextureAtlas(Gdx.files.internal("macken.pack"));
TextureRegion text=(TextureRegion)atlas.findRegion("imagename");
```