首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >跨类使用资源?

跨类使用资源?
EN

Stack Overflow用户
提问于 2011-09-02 22:15:38
回答 1查看 66关注 0票数 0

我有一个GameLoop类,其中定义了一个ParticleSystem对象。

ParticleSystem包含一个粒子对象数组--我不想为每个单独的粒子加载一个图像,我只想从GameLoop类中的源图像中提取--我怎样才能高效地这样做呢?

解决方案:

以下是丹·S帮我想出的:

代码语言:javascript
复制
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

然后在一个类中定义它:

代码语言:javascript
复制
rm = new ResourceManager(mContext);

然后将rm变量向下传递:

代码语言:javascript
复制
    ParticleSystem.Draw(rm, canvas);
   {
     Particle.Draw(rm, canvas);
    }

在粒子类中,我在构造函数中设置了一个字符串assetKey,因此我可以通过名称引用位图:

代码语言:javascript
复制
public void doDraw(ResourceManager rm, Canvas canvas) {
    canvas.drawBitmap(rm.getBitmap(AssetKey), xpos, ypos, null);
}

我希望这对其他人也有帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-09-02 22:21:02

在GameLoop的构造函数中,创建位图并在那里保存对它们的引用,将它们设置为最终变量,以防止意外分配。每当您创建一个新的粒子系统时,将它们传递给构造函数或在适当的setter方法中设置它们。

示例:

代码语言:javascript
复制
// in GameLoop definition

private Bitmap particleA;
private Bitmap particleB;

// somewhere in GameLoop constructor
particleA = BitmapFactor.decodeResource (activity.getResources(), R.drawable.particle_a);
particleB = BitmapFactor.decodeResource (activity.getResources(), R.drawable.particle_b);

// where you build your particle
Particle (GameLoop gl, ...) {
   oneLevelDown = new OneLevelDown(GameLoop gl, ...);
}

OneLevelDown (GameLoop gl, ...) {
   twoLevelDown = new TwoLevelDown(GameLoop gl, ...);
}

TwoLevelDown (GameLoop gl, ...) {
   particleABitmap = gl.getParticleA(); // simple getter
   particleBBitmap = gl.getParticleB(); // simple getter
}

一直把GameLoop传下去直到你说完为止。这可能不太有效,但一旦您掌握了喜欢的窍门,也请参阅本文中有关依赖注入的内容。

Java内存使用示例:

代码语言:javascript
复制
class Car{
   public int year;
   public int name;
}

// Object variables are references to an object's data.

Car a = new Car(); // first car object and variable. 
a.year = 1990;
a.name = "Sam";

Car b = new Car();// second car object and variable
b.year = 2000;
b.name = "Bob";

Car c = a; // third car **variable** but same car object as **a**

// primitives are different

int a = 23; // first variable, 4 bytes used
int b = 45; // second variable, 4 bytes used (and a total of 8)
int c = a;  // third variable, 4 bytes used (and a total of 12). c took on the value of a, but does not point to the same memory as a
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7289721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档