Android Bitmap 與 Drawable之間的區別和轉換

zhifeng687發表於2015-12-09


 

Bitmap - 稱作點陣圖,一般點陣圖的檔案格式字尾為bmp,當然編碼器也有很多如RGB565、RGB888。作為一種逐畫素的顯示物件執行效率高,但是缺點也很明視訊記憶體儲效率低。我們理解為一種儲存物件比較好。
Drawable - 作為Android平下通用的圖形物件,它可以裝載常用格式的影像,比如GIF、PNG、JPG,當然也支援BMP,當然還提供一些高階的視覺化物件,比如漸變、圖形等。

A bitmap is a Drawable. A Drawable is not necessarily a bitmap. Like all thumbs are fingers but not all fingers are thumbs.
Bitmap是Drawable . Drawable不一定是Bitmap .就像拇指是指頭,但不是所有的指頭都是拇指一樣.

The API dictates: API規定:

Though usually not visible to the application, Drawables may take a variety of forms: 儘管通常情況下對於應用是不可見的,Drawables 可以採取很多形式:

Bitmap: the simplest Drawable, a PNG or JPEG image. Bitmap: 簡單化的Drawable, PNG 或JPEG影像.
Nine Patch: an extension to the PNG format allows it to specify information about how to stretch it and place things inside of it.
Shape: contains simple drawing commands instead of a raw bitmap, allowing it to resize better in some cases.
Layers: a compound drawable, which draws multiple underlying drawables on top of each other.
States: a compound drawable that selects one of a set of drawables based on its state.
Levels: a compound drawable that selects one of a set of drawables based on its level.
Scale: a compound drawable with a single child drawable, whose overall size is modified based on the current level.

小結:

對比項 顯示清晰度 佔用記憶體 支援縮放 支援色相色差調整 支援旋轉 支援透明色 繪製速度 支援畫素操作

Bitmap 相同 大 是 是 是 是 慢 是
Drawable 相同 小 是 否 是 是 快 否


Drawable在記憶體佔用和繪製速度這兩個非常關鍵的點上勝過Bitmap

//轉換Bitmap to Drawable
Bitmap bitmap = new Bitmap (...);
Drawable drawable = new BitmapDrawable(bitmap);
 
//轉換Drawable to Bitmap
Drawable d = ImagesList.get(0);
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
  
//1、Drawable → Bitmap
public static Bitmap drawableToBitmap(Drawable drawable) {
          
        Bitmap bitmap = Bitmap
                        .createBitmap(
                                        drawable.getIntrinsicWidth(),
                                        drawable.getIntrinsicHeight(),
                                        drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                                        : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        //canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
}
 
//2、從資源中獲取Bitmap
Resources res=getResources();
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);
 
//3、Bitmap → byte[]
private byte[] Bitmap2Bytes(Bitmap bm){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
   }
 
//4、 byte[] → Bitmap
private Bitmap Bytes2Bimap(byte[] b){
            if(b.length!=0){
                return BitmapFactory.decodeByteArray(b, 0, b.length);
            }
            else {
                return null;
            }
      }

相關文章