(二十八)Android GDI之Surface&Canvas
最后更新于:2022-04-01 11:41:16
# Surface&Canvas
Canvas为在画布的意思。Android上层的作图几乎都通过Canvas实例来完成,其实Canvas更多是一种接口的包装。drawPaints ,drawPoints,drawRect,drawBitmap ...
[![image](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-05-05_572b1a2cba92c.gif "image")
](http://hi.csdn.net/attachment/201006/14/0_1276524262qcXC.gif)
### 1 Canvas与Surface之间本质关系
对于本节,我们不去研究Skia图形引擎本身,我们需要了解的我们的所做的图形到底放置到了那个地方,并且这个Canvas如何与Surface连接在一起的。
Canvas(Java)在C++Native层有一个Native Canvas的C++对象所对应。
lockCanvas()@java
Surface_lockCanvas@android_view_Surface.cpp
SurfaceControl->new Surface(control) @Surface.cpp
Surface: lock操作:
[](http://hi.csdn.net/attachment/201006/14/0_1276524263FdtA.gif)[![image](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-05-05_572b1a2ccb054.gif "image")](http://hi.csdn.net/attachment/201006/14/0_1276524264rrrr.gif)
GraphicBuffer :lock
getBufferMapper().lock GraphicBufferMapper ::lock
mAllocMod->lockgralloc_module_t::lock
通过SurfaceLock可取得Surface(mLockedBuffe)所对应的图形缓冲区地址。
(1) 建立与SkCanvas连接的位图设备,而该位图使用上面取得的图形缓冲区地址做自己的位图内存。
(2) 设置SkCanvas的作图目标设备为该位图。
通过该过程就建立起了SurfaceControl与Canvas之间的联系。
[](http://hi.csdn.net/attachment/201006/14/0_1276524266rhNg.gif)[![image](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-05-05_572b1a2cdc00c.gif "image")](http://hi.csdn.net/attachment/201006/14/0_1276524267jPRF.gif)
### 2 View:OnDraw的本源
不是使用OpenGL绘制时,Android在View属性发生变化,新建View时,或者Z-order发生变化时,需要对系统屏幕上的View重新绘制,此时我们的View会执行OnDraw(canvas),这个根源在哪里呢?
~~~
ViewRoot.Java
performTraversals(..)
…
draw()
canvas = surface.lockCanvas(dirty);
…
mView.draw(canvas);
draw(cavas)@view.java
background.draw(canvas);
onDraw(cavas)
dispatchDraw(cavas)
onDrawScrolbars(cavas)
surface.unlockCanvasAndPost(canvas);
~~~