Save the canvas, then restore why?

I often see the following code

canvas.save(). canvas translate or rotate some drawing canvas.restore 

I do not understand why we save and then restore. What is the point of destroying what we just did! I'm sure I have something missing Thanks

+8
android android canvas
source share
3 answers

What is the point of destroying what we just did!

You are not, really. If you just get away from the words, it seems that this can happen, but in fact it is not.

Think of it this way:

You have a series of really complex translations and turns that you want to apply in the same onDraw(Canvas) call. Now, since each translation / rotation that you apply to Canvas happens in order, you will have to undo the last settings in Canvas or somehow calculate your new settings based on the previous one before drawing what you want to draw. It will be very dirty, very fast.

Using canvas.save() and canvas.restore() is a ridiculously easy way to simplify this process.

By making adjustments related to Canvas in the save / restore block, you effectively isolate these settings so that what you want to draw next does not affect what you are drawing now.

Now let's explain the names a little better:

canvas.save() says that I want to keep the status of the current Canvas adjustments, so I can return to it later.

canvas.restore() says that I want to return the Canvas settings back the last time I called cavas.save()

The beauty of this is in its simplicity. If you already drew what you wanted to draw during the save / restore block, and you no longer need this setting for the next drawing, using this, you can discard these unnecessary settings and return to the state in which you want to start the next drawing from .

Hope this helps explain this!

+15
source share

When you have a background consisting of several objects, a great way is to keep this β€œstatic” background and only change the changed objects. This saves time (processor).

0
source share

Work with the canvas includes all methods of translation, scaling, rotation, skew on the canvas. The save () method saves the state until any of the above additions, restore () rewinds to the state in time when augmentation is not entered. In other words, you can save the preliminary state before any transformation of the canvas, perform your rotations and everything else you want during the process, but when your ready to rewind to the state to any increase.

0
source share

All Articles