教程总目录: http://blog.csdn.net/zqiang_55/article/details/50878524
Libgdx发展之初默认使用OpenGL ES 1.0,这是要求图片大小必须是2的n次方。但现在默认是使用的是2.0,这样就不必要求图片的大小。但是为了节约内存,还是推荐使用图片打包工具,将图片打包,这时使用的工具就是TexturePacker。
文章用到的工具下载: http://download.csdn.net/detail/zqiang_55/9480077
Texturepacker
下面的截图列出了对工具的一些说明
TextureAtlas
说白了TextureAtlas就是一个解析TexturePacker打包的图片一个工具。下面先看一下其类图
从类图可以知道,TextureAtlas继承了Disposable接口,因此在程序退出时需要调用dispose()方法。AtlasRegion是一个内部类,继承自TextureRegion
/** Loads the specified pack file using {@link FileType#Internal}, using the parent directory of the pack file to find the page
* images. */
public TextureAtlas (String internalPackFile) {
this(Gdx.files.internal(internalPackFile));
}
/** Loads the specified pack file, using the parent directory of the pack file to find the page images. */
public TextureAtlas (FileHandle packFile) {
this(packFile, packFile.parent());
}
/** Returns the first region found with the specified name. This method uses string comparison to find the region, so the result
* should be cached rather than calling this method multiple times.
* @return The region, or null. */
public AtlasRegion findRegion (String name) {
for (int i = 0, n = regions.size; i < n; i++)
if (regions.get(i).name.equals(name)) return regions.get(i);
return null;
}
/** Returns all regions with the specified name, ordered by smallest to largest {@link AtlasRegion#index index}. This method
* uses string comparison to find the regions, so the result should be cached rather than calling this method multiple times. */
public Array<AtlasRegion> findRegions (String name) {
Array<AtlasRegion> matched = new Array();
for (int i = 0, n = regions.size; i < n; i++) {
AtlasRegion region = regions.get(i);
if (region.name.equals(name)) matched.add(new AtlasRegion(region));
}
return matched;
}
测试用例,从网上找了4张图片,用TexturePacker打包之后如下图:
注意,用工具打包之后会生成2个文件.atlas和.png 2个文件,2个文件都需要拷贝到工程目录下,atlas文件是对png文件的描述。
TextureAtlas atlas;
AtlasRegion baidu, kugou, xiami, kuwo;
SpriteBatch batch;
@Override
public void create() {
atlas = new TextureAtlas(Gdx.files.internal("textureatlas.atlas"));
baidu = atlas.findRegion("baidu");
kugou = atlas.findRegion("kugou");
xiami = atlas.findRegion("xiami");
kuwo = atlas.findRegion("kuwo");
batch = new SpriteBatch();
}
@Override
public void render() {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(baidu, 10, 10);
batch.draw(kugou, 320, 240);
batch.draw(xiami, 10, 240);
batch.draw(xiami, 320, 10);
batch.end();
}
@Override
public void dispose() {
atlas.dispose();
batch.dispose();
}
测试结果