Android: Bitmap/Canvas/Drawable

栏目: IOS · Android · 发布时间: 6年前

内容简介:接触到自定义View之后,经常会遇到Canvas与Paint, 从使用上不难理解Paint, 但是对于Canvas和Bitmap以及Drawable之间的关系不是很清楚. 今天看了下代码, 尝试去区分一下.这个是Canvas类中写的, 如果我们要绘制什么的话, 需要:从这里我们就可以知道, 绘制调用是传到Canvas里, 但是绘制的位置是绘制在一个Bitmap上.

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

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类中写的, 如果我们要绘制什么的话, 需要:

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

从这里我们就可以知道, 绘制调用是传到Canvas里, 但是绘制的位置是绘制在一个Bitmap上.

那么Bitmap是啥呢?

Bitmap

位图, 其实可以理解为 int[] buffer , 也就是说这里有个缓存, 用来保存每个像素的信息

而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上

Drawable

Drawable是一个抽象, 描述所有可绘制的对象, 平时很少直接使用Drawable, 通常是使用drawable资源的方式获取Drawable对象.

资源类型 文件后缀 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) {
  }

}
复制代码

以上所述就是小编给大家介绍的《Android: Bitmap/Canvas/Drawable》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

算法技术手册

算法技术手册

[美]海涅曼 (Heineman.G.T.)、[美]波利切 (Pollice.G.)、[美]塞克欧 (Selkow.S.) / 东南大学出版社 / 2009-4 / 58.00元

创造稳定的软件需要有效的算法,但是程序设计者们很少能在问题出现之前就想到。《算法技术手册(影印版)》描述了现有的可以解决多种问题的算法,并且能够帮助你根据需求选择并实现正确的算法——只需要一定的数学知识即可理解并分析算法执行。相对于理论来说,本书更注重实际运用,书中提供了多种程序语言中可用的有效代码解决方案,可轻而易举地适合一个特定的项目。有了这本书,你可以: 解决特定编码问题或改进现有解决......一起来看看 《算法技术手册》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器