Understanding Android's Canvas.saveLayer(…)

坚强是说给别人听的谎言 提交于 2019-12-20 20:43:33

问题


I am hoping the saveLayer methods will allow me to do draw onto different "layers" and then once the drawing has finished, merge the layers with the canvas in whichever order i choose.

The obvious question is "why dont you just rearrange your drawing operations instead?" The answer is I can't:

I have a Path that I need to draw onto a Canvas. In the background/lowest z-index I want to draw the path closed and with a few additional points using a fill style. Then on top of that, I want to draw an outline of only the points that were originally in the Path.

Since I cannot undo the adding of points to the Path, my only choices are to clone the path, or to draw to a second layer which can later be placed on top of everything else.

saveLayer() seems to offer that functionality but it doesnt behave the way I was expecting. The basic flow of my operations is like this:

int overlay = canvas.saveLayer(...);
// drawing operations for my uppermost layer
...

int background = canvas.saveLayer(...);
// drawing operations for my background layer
...

// merge the offscreen background bitmap with the canvas:
canvas.restoreToCount(background);

// merge the offscreen overlay bitmap with the canvas:
canvas.restoreToCount(overlay);

When the code runs, the ordering of background and overlay have not changed at all; what gets drawn first is at the bottom and what gets drawn last is on top. Even stranger to me is that I can completely comment out both calls to restoreToCount() and nothing changes. According to the javadoc, nothing should be drawn to the canvas until a balancing restore() is invoked.

Obviously I am completely misunderstanding the function of this method. Can anybody help me to understand saveLayer's usage, or perhaps suggest an alternate way to layer my drawing operations?

Thx! Nick


回答1:


saveLayer() does not let you rearrange the layers in a random order. The only way to do it is to draw in offscreen bitmaps yourself. Note also that your view's parent will call save()/restore() around your onDraw() call, which will cause your layers to be composited.



来源:https://stackoverflow.com/questions/5121302/understanding-androids-canvas-savelayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!