Bitmap,BitmapDrawable,BitmapFactory的简单使用,以及AssetManager的使用


  1.将Bitmap封装成BitmapDrawable
  BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
 2.从BitmapDrawable中提取bitmap
  bitmap = bitmapDrawable.getBitmap();
 3.BitmapFactory中的方法可以从不同的数据源创建Bitmap对象
  bitmap = BitmapFactory.decodeStream(InputStream is);
 4.获取assets目录下的资源的方法:
  AssetManager assetManager = getResouce().getAssets();
  String [] filenames = assetManager.list(path);
  InputStream assets = assetManager.open(filenames[i]);
  bitmap = BitmapFactory.decodeStream(assets);
 5.判断bitmap是否回收
  BitmapDrawable bitmapDrawable = (BitmapDrawable) imageVew.getDrawable();

if(bitmapDrawable!=null&&!bitmapDrawable.getBitmap().isRecycled()){
bitmapDrawable.getBitmap().recycle();

}

下面是实现的一个案例(获取assets目录下的图片资源并将其显示在ImageView当中

public class MainActivity extends Activity implements OnClickListener{
	
	private Button nextBtn;
	private ImageView imageVew;
	private AssetManager assetManager;
	private String []images;
	private int mCurrentImg;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		assetManager = getResources().getAssets();
		try {
			images = assetManager.list("");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		imageVew = (ImageView)findViewById(R.id.image);
		nextBtn = (Button) findViewById(R.id.next);
		nextBtn.setOnClickListener(this);
	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(mCurrentImg>=images.length){
			mCurrentImg = 0;
		}
		
		// 直到找到图片的位置为止
		while(!images[mCurrentImg].endsWith("jpeg")){
			mCurrentImg++;
			if(mCurrentImg>=images.length){
				mCurrentImg = 0;
			}
		}
		
		InputStream assets=null;
		try {
			assets = assetManager.open(images[mCurrentImg++]);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		BitmapDrawable bitmapDrawable = (BitmapDrawable) imageVew.getDrawable();
		
		if(bitmapDrawable!=null&&!bitmapDrawable.getBitmap().isRecycled()){
			bitmapDrawable.getBitmap().recycle();
		}
		
		imageVew.setImageBitmap(BitmapFactory.decodeStream(assets));
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值