Android Bitmap对象


这个例子实现的是点击按钮播放assets中的下一张图片。

 

public class MainActivity extends Activity {

/***************************************
* Bitmap代表一个位图对象,可以利用BitmapFactory来创建Bitmap对象。
* BitmapDrawable是对bitmap的封装,可以通过BitmapDrawable.getBitmap来获得。
* 多用BitmapFactory工具类来获得Bitmap对象。一个Bitmap对象就表示一张位图,在处理的时候要小心因为资源没有释放导致的问题
*
* Bitmap可以通过多种方法生成Bitmap对象,比如从资源文件中用decodeResource(res,id)
* decodeStream(stream) decodefile.可以把BitmapFactory看成一个中介。核心还是Bitmap。
* 这样的话ImageView才能用setImageBitmap
*
***************************************/
String images[] = null;
AssetManager assets = null;
int currentImg = 0;
ImageView imageView;
Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

imageView = (ImageView) findViewById(R.id.imageView);
button = (Button) findViewById(R.id.button);

assets = getAssets();
try {
images = assets.list("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

if (currentImg >= images.length) {
currentImg = 0;
}

// 找到下一个图片
while (!images[currentImg].endsWith("jpg")
&& !images[currentImg].endsWith("png")
&& !images[currentImg].endsWith("gif")) {

currentImg++;
if (currentImg >= images.length) {
currentImg = 0;
}
}
InputStream fileStream = null;// 不能在try里面定义。
try {
fileStream = assets.open(images[currentImg++]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView
.getDrawable();
// 如果还未回收,强制回收
if (bitmapDrawable != null
&& !bitmapDrawable.getBitmap().isRecycled()) {
bitmapDrawable.getBitmap().recycle();
}
imageView.setImageBitmap(BitmapFactory.decodeStream(fileStream));
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}