天天看點

Android Bitmap

Android Bitmap對象

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

}