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));
}
}