Android: Bitmap/Canvas/Drawable

简介

接触到自定义View以后,常常会遇到Canvas与Paint, 从使用上不难理解Paint, 可是对于Canvas和Bitmap以及Drawable之间的关系不是很清楚. 今天看了下代码, 尝试去区分一下.java

Canvas

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

  1. 一个Bitmap去持有像素
  2. 一个Canvas来托管绘制调用, 而且绘制在Bitmap上
  3. 一个绘制原型, 好比矩形, path, text, Bitmap
  4. 一个画笔, 用来描述绘制的颜色和样式

从这里咱们就能够知道, 绘制调用是传到Canvas里, 可是绘制的位置是绘制在一个Bitmap上.缓存

那么Bitmap是啥呢?bash

Bitmap

位图, 其实能够理解为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资源的方式获取Drawable对象.code

资源类型 文件后缀 Drawable类型
Bitmap File .png .jpg .gif BitmapDrawable
Nine-Patch File .9.png NinePatchDrawable
Shape Drawable .xml ShapeDrawable
State List .xml StateListDrawable

与View的关系

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) {
  }

}
复制代码

总结

  • Bitmap只是一个存储格式, 存储了一个矩形区域内各像素点的信息. 这种格式适合显示, 可是存储效率低.
  • Canvas一样是一个矩形区域, 可是他没有边界, 咱们能够在上面调用任意drawXXX开头的方法绘制到引用的Bitmap上. 同时提供对图形的处理, 好比裁剪, 缩放, 旋转(须要Matrix对象配合使用). 因此Canvas与其说是画布, 不如说是一个绘制工具
  • Drawable表示一个能够被绘制的图形对象, 以及一些可视化对象, 好比渐变. 各个不一样的Drawable子类能够定义不一样的绘制方法, 其本质仍是经过Canvas绘制到Bitmap上.

若有问题, 欢迎指出, 谢谢wcomponent

相关文章
相关标签/搜索