【发布时间】:2015-02-03 10:10:39
【问题描述】:
如何使用 .assets.load("file", file.type) 加载精灵,在这种情况下,精灵的文件类型应该是什么?
【问题讨论】:
如何使用 .assets.load("file", file.type) 加载精灵,在这种情况下,精灵的文件类型应该是什么?
【问题讨论】:
我猜,您通常不会直接加载 Sprite,而是加载它的是 Texture 并从中创建一个 Sprite。
因此,您调用assets.load("file", Texture.class),然后使用您加载的Texture 创建一个Sprite:Sprite sprite = new Sprite(asstes.get("file", Texture.class))。
但我建议你使用TextureAtlas 而不是Texture。TextureAtlas 是某种“纹理集合”,它基本上是一个大 Texture,它本身包含所有单个 Textures。
您可以使用 assets.load("atlas", TextureAtlas.class)
加载它
并使用:
TextureAtlas atlas = assets.get("atlas", TextureAtlas.class).
然后您可以像这样创建您的Sprite:Sprite sprite = atlas.createSprite("spriteName");
要创建TextureAtlas,您可以使用TexturePacker。
【讨论】:
不建议直接加载精灵。当 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);
【讨论】:
TextureAtlas 和atlas.createSprite(spritename) 创建它,而不是从AtlasRegion 创建一个新的Sprite。另外TextureFilter可以在TexturePacker的配置中设置,所以是为整个TextureAtlas设置的。
resume() 和 resize() 方法中手动重新加载它们。为了避免这种头痛,我建议使用AssetManager。