首页 > 代码库 > libgdx学习记录19——图片动态打包PixmapPacker

libgdx学习记录19——图片动态打包PixmapPacker

libgdx中,opengl 1.x要求图片长宽必须为2的整次幂,一般有如下解决方法

1. 将opengl 1.x改为opengl 2.0。(libgdx 1.0版本后不支持1.x,当然不存在这个问题,这里针对的是0.9.9版本)

2. 使用TexturePacker将图片打包好然后作成一张大图添加进来。

第二种方法是常用方法,但是不太灵活,添加、删除某些图片不太方便,改动较大。这里可以考虑使用PixmapPacker将图片进行动态打包。

主要方法:

pack(String name, Pixmap pixmap) 打包某个图片,并制定名称

generateAtlas( TextureFilter minFilter, TextureFilter magFilter, boolean useMipMap ) 生成图片资源包

示例代码:

 1 package com.fxb.newtest;
 2 
 3 import com.badlogic.gdx.ApplicationAdapter;
 4 import com.badlogic.gdx.Gdx;
 5 import com.badlogic.gdx.graphics.GL10;
 6 import com.badlogic.gdx.graphics.Pixmap;
 7 import com.badlogic.gdx.graphics.Pixmap.Format;
 8 import com.badlogic.gdx.graphics.Texture.TextureFilter;
 9 import com.badlogic.gdx.graphics.g2d.PixmapPacker;
10 import com.badlogic.gdx.graphics.g2d.SpriteBatch;
11 import com.badlogic.gdx.graphics.g2d.TextureAtlas;
12 import com.badlogic.gdx.graphics.g2d.TextureRegion;
13 
14 public class Lib019_TexturePack extends ApplicationAdapter{
15 
16     TextureAtlas atlas;
17     TextureRegion region1, region2;
18     SpriteBatch batch;
19     
20     @Override
21     public void create() {
22         // TODO Auto-generated method stub
23         super.create();
24         
25         PixmapPacker packer = new PixmapPacker( 512, 512, Format.RGB565, 2, true );
26         //packer.pack( "first", pixmap1 );
27         Pixmap pixmap1 = new Pixmap( Gdx.files.internal( "data/badlogic.jpg" ) );
28         Pixmap pixmap2 = new Pixmap( Gdx.files.internal( "data/pal4_1.jpg" ) );
29         packer.pack( "first", pixmap1 );
30         packer.pack( "second", pixmap2 );
31         
32         atlas = packer.generateTextureAtlas( TextureFilter.Nearest, TextureFilter.Nearest, false );
33         region1 = atlas.findRegion( "first" );
34         region2 = atlas.findRegion( "second" );
35         
36         pixmap1.dispose();
37         pixmap2.dispose();
38         
39         batch = new SpriteBatch();
40     }
41 
42     @Override
43     public void render() {
44         // TODO Auto-generated method stub
45         super.render();
46         Gdx.gl.glClearColor( 0, 1, 1, 1 );
47         Gdx.gl.glClear( GL10.GL_COLOR_BUFFER_BIT );
48         
49         batch.begin();
50         batch.draw( region1, 10, 10 );
51         batch.draw( region2, 20+region1.getRegionWidth(), 10 );
52         batch.end();
53         
54     }
55 
56     @Override
57     public void dispose() {
58         // TODO Auto-generated method stub
59         atlas.dispose();
60         super.dispose();
61     }
62 
63 }

运行结果: