java跨类使用资源?
我有一个GameLoop类,其中定义了ParticleSystem对象
ParticleSystem包含一组粒子对象——我不想为每个单独的粒子加载一个图像,我只想能够从GameLoop类中的源图像中绘制——我怎样才能高效地做到这一点
解决方案:
以下是Dan S帮我想到的:
public class ResourceManager {
Context mContext;
public final HashMap<String, Bitmap> Texture = new HashMap<String, Bitmap>();
//Constructor
public ResourceManager(Context context)
{
mContext = context;
Texture.put("particle1", loadBitmap(R.drawable.particle1));
}
public Bitmap getBitmap(String key)
{
return Texture.get(key);
}
/** Load an image */
protected Bitmap loadBitmap(int id) { return BitmapFactory.decodeResource(mContext.getResources(), id); }
} //End ResourceManager
然后在类中定义它:
rm = new ResourceManager(mContext);
然后向下传递rm变量:
ParticleSystem.Draw(rm, canvas);
{
Particle.Draw(rm, canvas);
}
在粒子类中,我在构造函数中设置了一个字符串assetKey,这样我就可以通过一个名称来引用位图:
public void doDraw(ResourceManager rm, Canvas canvas) {
canvas.drawBitmap(rm.getBitmap(AssetKey), xpos, ypos, null);
}
我希望这对其他人也有帮助
# 1 楼答案
在GameLoop的构造函数中,创建位图并在其中保留对它们的引用,将它们设置为最终变量,以增加对意外赋值的保护。无论何时创建新粒子系统,都要将它们传递给构造函数或使用适当的setter方法进行设置
示例:
继续传递GameLoop直到你完成。这可能感觉效率不高,但一旦你掌握了窍门,你会喜欢的,也可以看看这篇关于Dependency Injection的文章
Java内存使用示例: