Android Bitmap

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

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值