標籤:c style class blog code java
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 @Override21 public void create() {22 // TODO Auto-generated method stub23 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 @Override43 public void render() {44 // TODO Auto-generated method stub45 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 @Override57 public void dispose() {58 // TODO Auto-generated method stub59 atlas.dispose();60 super.dispose();61 }62 63 }
運行結果: