我试图在另一个线程中从磁盘加载图像,以免减慢我的绘制线程,但问题是当保存位图的对象被传输到新线程时,它们有不同的指针。我不完全确定Java如何跨可乘线程处理指针,但我正在寻找一种解决方案,使两个线程都使用同一个对象(浅拷贝)而不是线程之间对象的深度拷贝。
这是我的代码
new LoadImageTask().execute(ThisTimeDrawBitmaps.indexOf(bitmapWrapper), gameEngine);
private class LoadImageTask extends AsyncTask {
protected BitmapWrapper LoadImage(BitmapWrapper bitmapWrapper, GameEngine gameEngine) {
//loading the image in a temp object to avoid fatal error 11
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = true;
Bitmap tempImage = BitmapFactory.decodeResource(Sceptrum.GetResources, bitmapWrapper.getID(), options);
tempImage = Bitmap.createScaledBitmap(bitmapWrapper.getBitmap(), (int) (bitmapWrapper.getBitmap().getWidth() * gameEngine.getScale()), (int) (bitmapWrapper.getBitmap().getHeight() * gameEngine.getScale()), false);
//so that the image can be gc.
Bitmap RemovePointer = bitmapWrapper.getBitmap();
//to avoid fatal error 11
bitmapWrapper.setBitmap(tempImage);
//removing the old image.
RemovePointer.recycle();
return bitmapWrapper;
}
@Override
/**
* add the bitmapwrapper you want to load and make sure to add the GameEngine as the last parameter.
*/
protected Object doInBackground(Object... params) {
for (int i = 0; i < params.length - 1; i++) {
return LoadImage(ThisTimeDrawBitmaps.get((Integer) params[i]), (GameEngine) params[params.length - 1]);
}
return null;
}
}
public class BitmapWrapper{
private Bitmap bitmap;
/**
* Use only to send the bitmap as a parameter. To modify or read data to/from the bitmap use the methods provided by BitmapWrapper.
* @return
*/
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
private int id;
public int getID()
{
return id;
}
private Point originalSize;
public Point getOriginalSize() {
return originalSize;
}
public BitmapWrapper(Bitmap bitmap, int ID) {
this.setBitmap(bitmap);
id = ID;
originalSize = new Point(bitmap.getWidth(), bitmap.getHeight());
}
public int getWidth()
{
return bitmap.getWidth();
}
public int getHeight()
{
return bitmap.getHeight();
}
public void createScaledBitmap(GameEngine gameEngine)
{
bitmap = Bitmap.createScaledBitmap(bitmap, (int) (originalSize.x * gameEngine.getScale()), (int) (originalSize.y * gameEngine.getScale()), false);
}
public void CreateBitmap()
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
bitmap = BitmapFactory.decodeResource(Sceptrum.GetResources, id, options);
}
}