Bitmap和Drawable的區別,為什麼要用bitmap?
謝邀.1. 注意看 Drawable 的注釋:
* A Drawable is a general abstraction for "something that can be drawn." Most
* often you will deal with Drawable as the type of resource retrieved for
* drawing things to the screen; the Drawable class provides a generic API for
* dealing with an underlying visual resource that may take a variety of forms.
* Unlike a {@link android.view.View}, a Drawable does not have any facility to
* receive events or otherwise interact with the user.
再看看其類定義:
public abstract class Drawable {
......
}
也就是說 Drawable 只是一個抽象概念, 表示"something that can be drawn".
Drawable 的注釋下面還有一段話:
Though usually not visible to the application, Drawables may take a variety of forms:
1. Bitmap: the simplest Drawable, a PNG or JPEG image.
2. Nine Patch: an extension to the PNG format allows it to specify information about how to stretch it and place things inside of it.
3. Shape: contains simple drawing commands instead of a raw bitmap, allowing it to resize better in some cases.
4. Layers: a compound drawable, which draws multiple underlying drawables on top of each other.
5. States: a compound drawable that selects one of a set of drawables based on its state.
6. Levels: a compound drawable that selects one of a set of drawables based on its level.
7. Scale : a compound drawable with a single child drawable, whose overall size is modified based on the current level.
那麼形式就比較明朗了, Drawable 是一個抽象的概念, 而 Bitmap 是其存在的實體之一.
2. 我們來看 Bitmap 類的定義:
public final class Bitmap implements Parcelable {
......
}
細心的同學會發現, Bitmap 並沒有實現 Drawable,那麼他們倆是如何聯繫起來的呢? 答案是 BitmapDrawable.:
public class BitmapDrawable extends Drawable {
......
}
private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np,
Rect pad, Rect layoutBounds, String srcName) {
if (np != null) {
return new NinePatchDrawable(res, bm, np, pad, layoutBounds, srcName);
}
return new BitmapDrawable(res, bm);
}
通過 BitmapDrawable 的構造函數,使得 Bitmap 可以轉換為 Drawable.
同樣, BitmapDrawable 的 getBitmap 方法也會返回 bitmap對象:
/**
* Returns the bitmap used by this drawable to render. May be null.
*/
public final Bitmap getBitmap() {
return mBitmapState.mBitmap;
}
可以簡單地理解為 Bitmap 儲存的是 像素信息,Drawable 儲存的是 對 Canvas 的一系列操作。
而 BitmapDrawable 儲存的是「把 Bitmap 渲染到 Canvas 上」這個操作。前者重數據,後者重行為。類似 iOS 中 CGImage 和 UIImage 的關係,Drawable 經過封裝甚至可以實現網路載入的功能,而 Bitmap 不能。
Bitmap是用來顯示的實際數據,它在概念上隸屬於Drawable,但是與Drawable之間不是繼承關係。
drawable原理?
推薦閱讀:
※安卓開發工程師到一個新公司的第一天一般幹嘛呢?
※如何評論 360 開源的 Android 插件機制 Droid Plugin?
※Android 如何賺錢?
※Android中View, SurfaceView的繪圖和GLSurfaceView繪圖有區別嗎?
TAG:Android開發 |