接觸到自定義View以後,常常會遇到Canvas與Paint, 從使用上不難理解Paint, 可是對於Canvas和Bitmap以及Drawable之間的關係不是很清楚. 今天看了下代碼, 嘗試去區分一下.java
The Canvas class holds the "draw" calls. To draw something, you need
4 basic components: A Bitmap to hold the pixels, a Canvas to host
the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect,
Path, text, Bitmap), and a paint (to describe the colors and styles for the
drawing).
複製代碼
這個是Canvas類中寫的, 若是咱們要繪製什麼的話, 須要:canvas
從這裏咱們就能夠知道, 繪製調用是傳到Canvas裏, 可是繪製的位置是繪製在一個Bitmap上.緩存
那麼Bitmap是啥呢?bash
位圖, 其實能夠理解爲int[] buffer
, 也就是說這裏有個緩存, 用來保存每一個像素的信息ide
而Canvas類中有個Bitmap對象:工具
public class Canvas extends BaseCanvas {
...
// may be null
private Bitmap mBitmap;
public Canvas(@NonNull Bitmap bitmap) {
...
mBitmap = bitmap;
...
}
public void setBitmap(@Nullable Bitmap bitmap) {
...
mBitmap = bitmap;
}
}
複製代碼
所以實際繪製是繪製在Canvas所持有的Bitmap上spa
Drawable是一個抽象, 描述全部可繪製的對象, 平時不多直接使用Drawable, 一般是使用drawable資源的方式獲取Drawable對象.code
資源類型 | 文件後綴 | Drawable類型 |
---|---|---|
Bitmap File | .png .jpg .gif | BitmapDrawable |
Nine-Patch File | .9.png | NinePatchDrawable |
Shape Drawable | .xml | ShapeDrawable |
State List | .xml | StateListDrawable |
public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
...
private Drawable mBackground; // 背景
...
public void setBackground(Drawable background) {
setBackgroundDrawable(background);
}
@Deprecated
public void setBackgroundDrawable(Drawable background) {
...
mBackground = background;
...
}
public void draw(Canvas canvas) {
...
// Step 1, draw the background, if needed
if (!dirtyOpaque) {
drawBackground(canvas);
}
...
}
private void drawBackground(Canvas canvas) {
final Drawable background = mBackground;
...
background.draw(canvas);
...
}
@Override
protected void onDraw(Canvas canvas) {
}
}
複製代碼
若有問題, 歡迎指出, 謝謝wcomponent