初學Android,圖形影象之使用Bitmap和BitmapFactory(二十四)
阿新 • • 發佈:2018-12-23
Bitmap代表一張點陣圖,BitmapDrawable裡封裝的圖片就是一個Bitmap物件.把Bitmap物件包裝成BitmapDrawable物件,可以呼叫Bitmapdrawable的構造器
BitmapDrawable drawable = new BitmapDrawable(bitmap);
如果要獲取BitmapDrawable所包裝的bitmap物件,可以呼叫getBitmap()方法
Bitmap bitmap = drawable.getBitmap();
如果需要訪問其它儲存路徑的圖片,需要藉助於BitmapFactory來解析,建立Bitmap物件
下面製作一個assets/資料夾下圖片的圖片檢視器,在assets下隨便放幾張影象檔案
每點一次按鈕,ImageView的圖片就會切換到另一張package WangLi.Graphics.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 BitmapTest extends Activity { /** Called when the activity is first created. */ String[] images = null; AssetManager assets = null; int currentImg = 0; ImageView image; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); image = (ImageView)findViewById(R.id.image); try { assets = getAssets(); //獲取/assets/目錄下所有檔案 images = assets.list(""); } catch(IOException e) { e.printStackTrace(); } //獲取bn按鈕 final Button next = (Button)findViewById(R.id.next); //為bn按鈕繫結事件監聽器,該監聽器將會檢視下一張圖片 next.setOnClickListener(new OnClickListener(){ public void onClick(View sources) { //如果發生陣列越界 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)); } }); } }
點一下按鈕
一直點下去,迴圈出現資料夾下的圖片
另外在測試過程中,感覺圖片載入的比較慢,不知道有什麼優化的方法?