本文中既读取了assets中的原始资源,又练习了Bitmap和BitmapFactory的使用。
Bitmap代表一张位图,BitmapDrawable里封装的图片就是一个Bitmap对象,把一个Bitmap对象包装成BitmapDrawable对象,可以使用BitmapDrawable的构造器:
BitmapDrawable drawable=new BitmapDrawable(bitmap);
获取一个BitmapDrawable所包装的Bitmap对象:
Bitmap bitmap=drawable.getBitmap();
另外,Bitmap还提供了一些静态方法来创建新的Bitmap对象,如下:
注意:由于手机系统的内存比较小,如果系统不停地去解析、创建Bitmap对象,可能由于前面创建的Bitmap所占用的内存还没有回收而导致程序运行引发OutOfMemory错误。所以Android使用下面两个方法分别判断Bitmap是否已经回收和强制回收:
boolean isRecycled():返回该Bitmap对象是否已被回收。
void recycle():强制一个Bitmap对象立即回收自己。
下面开发一个查看assets目录下图片的图片查看器,实现自动搜寻该目录下的下一张图片,代码如下:
Activity:
package com.lovo.bitmaptest; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.content.res.AssetManager; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { String[] images = null; AssetManager assets = null; int currentImg = 0; ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); image = (ImageView) findViewById(R.id.activity_main_image); try { // 获得AssetManager对象 assets = getAssets(); // 获取/assets目录下的所有文件 images = assets.list(""); } catch (IOException e) { e.printStackTrace(); } // 获取按钮 final Button next = (Button) findViewById(R.id.activity_main_btn); next.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 如果发生数组越界 if (currentImg >= images.length) { currentImg = 0; } // 如果当前文件不是图片则找到下一个图片文件 while (!images[currentImg].endsWith(".png") && !images[currentImg].endsWith(".jpg") && !images[currentImg].endsWith(".gif")) { currentImg++; // 如果数组已经发生越界 if (currentImg >= images.length) { currentImg = 0; } } InputStream assetFile = null; try { // 打开指定资源对应的输入流 assetFile = assets.open(images[currentImg++]); } catch (IOException e) { e.printStackTrace(); } BitmapDrawable bitmapDrawable = (BitmapDrawable) image .getDrawable(); // 如果图片未回收,先强制回收该图片 if (bitmapDrawable != null && !bitmapDrawable.getBitmap().isRecycled()) { bitmapDrawable.getBitmap().recycle(); } // 改变ImageView显示的图片 image.setImageBitmap(BitmapFactory.decodeStream(assetFile)); } }); } }
布局XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" > <Button android:id="@+id/activity_main_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下一张" /> <ImageView android:id="@+id/activity_main_image" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>