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

时间:2022-05-10 01:50:59

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 ) 生成图片资源包

示例代码:

 package com.fxb.newtest;

 import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.PixmapPacker;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion; public class Lib019_TexturePack extends ApplicationAdapter{ TextureAtlas atlas;
TextureRegion region1, region2;
SpriteBatch batch; @Override
public void create() {
// TODO Auto-generated method stub
super.create(); PixmapPacker packer = new PixmapPacker( 512, 512, Format.RGB565, 2, true );
//packer.pack( "first", pixmap1 );
Pixmap pixmap1 = new Pixmap( Gdx.files.internal( "data/badlogic.jpg" ) );
Pixmap pixmap2 = new Pixmap( Gdx.files.internal( "data/pal4_1.jpg" ) );
packer.pack( "first", pixmap1 );
packer.pack( "second", pixmap2 ); atlas = packer.generateTextureAtlas( TextureFilter.Nearest, TextureFilter.Nearest, false );
region1 = atlas.findRegion( "first" );
region2 = atlas.findRegion( "second" ); pixmap1.dispose();
pixmap2.dispose(); batch = new SpriteBatch();
} @Override
public void render() {
// TODO Auto-generated method stub
super.render();
Gdx.gl.glClearColor( 0, 1, 1, 1 );
Gdx.gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); batch.begin();
batch.draw( region1, 10, 10 );
batch.draw( region2, 20+region1.getRegionWidth(), 10 );
batch.end(); } @Override
public void dispose() {
// TODO Auto-generated method stub
atlas.dispose();
super.dispose();
} }

运行结果:

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