我知道这是使用位图的常见问题,但我不知道如何继续使用示例。特别是因为图像视图的大小并不大,你会说它应该会导致内存错误。我认为这是因为我经常创建位图,而不是一旦蚂蚁每隔5秒显示一次就创建它,但不知道如何去做。首先创建位图的代码。OutOfMemory错误需要解决方案
java类trapViews
:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int x = 20;
Random r = new Random();
int i1 = r.nextInt(900 - 200) + 200;
rnd = new Random();
//Linke Seite
System.gc();
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.stachelnstart);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(image, i1, 300, true);
float left = (float) 0;
float top = (float) (getHeight() - resizedBitmap.getHeight());
canvas.drawBitmap(resizedBitmap, left, top, paint);
//rechte Seite
Bitmap images = BitmapFactory.decodeResource(getResources(), R.drawable.stachelnstart1);
Bitmap resizedBitmaps = Bitmap.createScaledBitmap(images, getWidth()-resizedBitmap.getWidth()-OwlHole, 300, true);
float left1 = (float) (getWidth() - resizedBitmaps.getWidth());
float top1 = (float) (getHeight() - resizedBitmaps.getHeight());
canvas.drawBitmap(resizedBitmaps, left1, top1, paint);
}
}
创建右边和屏幕的左侧具有随机长度的可绘制。
现在,我称这种现象为MainActivity
每5秒一个Handler
:
final Handler h = new Handler();
Runnable r = new Runnable() {
public void run() {
System.gc();
traps();
h.postDelayed(this,5000); // Handler neustarten
}
}
private void traps() {
container = (ViewGroup) findViewById(R.id.container);
trapViews tv = new trapViews(this);
container.addView(tv,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
//tV.setImageCount(8);
h.postDelayed(r, 5000);
}
首先,它的工作就像我想要的工作。但每次出现新的drawable时,我的游戏都会滞后,并且经过5-6次创建一次后会崩溃
System.gc()
和bitmap.recycle
函数不能很好地工作。有人有解决方案吗?
为什么在方法范围内一次又一次地读取和解码?在构建对象并重用它时执行一次。 – duffymo
是啊这就是我想要做的。但我没有得到如何。你有什么样的例子吗? – Hendrx
在Runnable/Callable类构造函数中或在拥有onDraw的类中执行此操作。我更喜欢第二个。 – duffymo