android中Bit地图导致的内存溢出

android中Bitmap导致的内存溢出

今天研究了下android原生态实现游戏,主要是使用自定义View类,通过不断调用其onDraw方法实现界面刷新,完成动。但是由于是研究学习阶段,难免会有错误,我将使用到的图片在ondraw方法中加载了,这样导致每次重新绘制都要加载Bitmap对象,这样导致了大量的内存使用,最终内存不堪重负,窗体自动销毁。最后,将需要使用到的图片放在了声明部分,果然问题解决了,所以,想记录下来希望看到这篇文章的朋友都能够少走弯路。

// 素材图片
	Bitmap bmap_bg = BitmapFactory.decodeResource(getResources(), R.drawable.map3_1);
	Bitmap bmap_fighter = BitmapFactory.decodeResource(getResources(), R.drawable.fighter_96);
	
protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		Paint paint = new Paint();
		
		// 绘制背景
		//Bitmap bmap_bg = BitmapFactory.decodeResource(getResources(), R.drawable.map3_1);
		canvas.drawBitmap(bmap_bg, 0,0, paint);
		
		//Bitmap bmap_fighter = BitmapFactory.decodeResource(getResources(), R.drawable.fighter_72);
		
		//图片的尺寸
		int width = bmap_fighter.getWidth();
		int height = bmap_fighter.getHeight();
		
		canvas.drawBitmap(bmap_fighter, px-width/2, py-height/2, paint);
	}