我知道这是使用位图的一个常见问题,但我不知道如何继续这个例子。特别是因为图像视图的大小不大,你会说它应该导致内存错误。我认为这是因为我经常创建位图而不是创建它,一旦蚂蚁每隔五秒显示一次,但不知道该怎么做。首先是创建位图的代码。
java class 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);
}
}
在屏幕的右侧和左侧以随机长度创建一个drawable。
现在我使用MainActivity
Handler
中每5秒调用一次
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);
}
首先,它的工作方式就像我希望它能够工作一样。但每当一个新的抽签出现时,我的游戏就会滞后,并且在5-6次之后创建一个崩溃的
System.gc()
和bitmap.recycle
功能效果不佳。有人有解决方案吗?
答案 0 :(得分:1)
请记住在替换位图后或当它不再可见时调用Bitmap.recycle()。 创建多个位图不是问题,而是在不使用循环来释放内存的情况下留下未使用的对象。
答案 1 :(得分:1)
你每隔5秒创建一次位图,这不是一个好主意,因为它们总是一样的。你应该创建一次
trapViews extends View{
Bitmap image;
Bitmap resizedBitmap;
//rechte Seite
Bitmap images ;
Bitmap resizedBitmaps;
trapViews(Context c){
image = BitmapFactory.decodeResource(getResources(), R.drawable.stachelnstart);
images = BitmapFactory.decodeResource(getResources(), R.drawable.stachelnstart1);
}
@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
//I have left this bitmap in the here as it is affected by the random int
resizedBitmap = Bitmap.createScaledBitmap(image, i1, 300, true);
float left = (float) 0;
float top = (float) (getHeight() - resizedBitmap.getHeight());
canvas.drawBitmap(resizedBitmap, left, top, paint);
//create this bitmap here as getWidth() will return 0 if created in the view's constructor
if(resizedBitmaps == null)
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);
}
}