2014-12-05 44 views

回答

3

我猜,你usualy不直接加載Sprite,但你加載它Texture並創建一個Sprite出來。
因此,您致電assets.load("file", Texture.class),然後創建一個Sprite與您加載的Texture
Sprite sprite = new Sprite(asstes.get("file", Texture.class))

但我建議您使用TextureAtlas而不是Texture
A TextureAtlas是某種「紋理集合」,它基本上是一個大的Texture,它本身具有所有單個的Texture
您可以使用assets.load("atlas", TextureAtlas.class)
加載它並使用它: TextureAtlas atlas = assets.get("atlas", TextureAtlas.class)
然後,您可以創建Sprite這樣的:
Sprite sprite = atlas.createSprite("spriteName");

要創建一個TextureAtlas你可以使用TexturePacker

1

不建議直接加載精靈。當Android上發生上下文丟失時,它將釋放佔用您已加載資源的內存。因此,在上下文丟失後直接訪問您的資產會立即使恢復的應用程序崩潰。

爲了防止上述問題,您應該使用AssetManager加載和存儲資源,如紋理,位圖字體,瓷磚貼圖,聲音,音樂等。通過使用AssetManager,您只需加載一次資產。

我建議這樣做的方法如下:

// load texture atlas 
final String spriteSheet = "images/spritesheet.pack"; 
assetManager.load(spriteSheet, TextureAtlas.class); 
// blocks until all assets are loaded 
assetManager.finishedLoading(); 
// all assets are loaded, we can now create our TextureAtlas object 
TextureAtlas atlas = assetManager.get(spriteSheet); 

// (optional) enable texture filtering for pixel smoothing 
for (Texture t: atlas.getTextures()) 
    t.setFilter(TextureFilter.Linear, TextureFilter.Linear); 

// Create AtlasRegion instance according the given <atlasRegionName> 
final String atlasRegionName = "regionName"; 
AtlasRegion atlasRegion = atlas.findRegion(atlasRegionName); 

// adjust your sprite position and dimensions here 
final float xPos = 0; 
final float yPos = 0; 
final float w = asset.getWidth(); 
final float h = asset.getHeight(); 

// create sprite from given <atlasRegion>, with given dimensions <w> and <h> 
// on the position of the given coordinates <xPos> and <yPos> 
Sprite spr = new Sprite(atlasRegion, w, h, xPos, yPos); 
+1

而不是創建一個新的'Sprite'了'AtlasRegion'的,你可以直接從'TextureAtlas'用'atlas.createSprite(創造它spritename)'。同樣'TextureFilter'可以在'TexturePacker'的配置中設置,因此它被設置爲整個'TextureAtlas'。 – Springrbua 2014-12-05 12:41:29

+0

這個答案不完全正確。使用或不使用AssetManager時,libgdx中的紋理會自動*託管*,因此會在上下文丟失後自動重新加載。 – Tenfour04 2014-12-05 16:23:12

+0

在libgdx中,您可以擁有託管和非託管紋理。因此,確實可以通過確保自動管理紋理來避免使用AssetManager。這是從FileHandle加載紋理時的情況,但如果它們是從Pixmap加載的,則必須在'resume()'或者'resize()'方法中手動重新加載它們。爲了避免這種頭痛,我建議使用'AssetManager'。 – Gio 2014-12-05 21:18:39