Bitmap和Drawable的關係、區別
阿新 • • 發佈:2019-02-04
1. 注意看 Drawable 的註釋:
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 ofeach 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 {
......
}
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;
}