内容简介:接触到自定义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类中写的, 如果我们要绘制什么的话, 需要:
- 一个Bitmap去持有像素
- 一个Canvas来做主绘制调用, 并且绘制在Bitmap上
- 一个绘制原型, 比如矩形, path, text, Bitmap
- 一个画笔, 用来描述绘制的颜色和样式
从这里我们就可以知道, 绘制调用是传到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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
密码学原理与实践
[加]Douglas R.Stinson / 冯登国 / 电子工业出版社 / 2009年 / 55.00元
冯登国(FENG Dengguo,1965.5~), 现为中国科学院软件所研究员、博士生导师,信息安全国家重点实验室主任,国家计算机网络入侵防范中心主任,国家信息化专家咨询委员会委员。目前主要从事信息与网络安全方面的研究与开发工作。一起来看看 《密码学原理与实践》 这本书的介绍吧!