Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Android's Canvas.saveLayer(...)

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

like image 441
Nick Avatar asked Feb 25 '11 18:02

Nick


1 Answers

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.

like image 60
Romain Guy Avatar answered Oct 24 '22 22:10

Romain Guy