Custom controls often encounter the Ondraw () method of overriding view, and the Ondraw () method is often designed to both the save () and restore () methods. The two matching occurrences are used to save the state of the canvas and remove the saved state. The specific functions are as follows:
1.save (): Used to save the stateof the canvas , the code after the Save () method can call the canvas 's panning, Zoom, rotate, crop and so on!
2.restore (): Used to restore the previously saved state of the Canvas, preventing the Save () method code from following the the actions that the Canvas performs continue to have an impact on subsequent drawing, which can be avoided by this method!
Here's a quick example to illustrate the first piece of code:
Private class DemoView extends View {private Paint mpaint;private Bitmap bitmap1;private Bitmap bitmap2;public DemoView (Co ntext context) {super (context); mpaint = new Paint (); bitmap1 = Bitmapfactory.decoderesource (Getresources (), R.DRAWABLE.A); bitmap2 = Bitmapfactory.decoderesource (Getresources (), r.drawable.b);} @Overrideprotected void OnDraw (canvas canvas) {canvas.drawbitmap (bitmap1, 0, 0, mpaint); Canvas.scale (5f, 5f); Canvas.drawbitmap (BITMAP2, Max, mpaint); Super.ondraw (canvas);}}
The simple example is to draw two pictures, and after the first painting, the canvas is magnified 5 times times, the effect:
Below, let's change the code slightly, as follows:
Private class DemoView extends View {private Paint mpaint;private Bitmap bitmap1;private Bitmap bitmap2;public DemoView (Co ntext context) {super (context); mpaint = new Paint (); bitmap1 = Bitmapfactory.decoderesource (Getresources (), R.DRAWABLE.A); bitmap2 = Bitmapfactory.decoderesource (Getresources (), r.drawable.b);} @Overrideprotected void OnDraw (canvas canvas) {canvas.drawbitmap (bitmap1, 0, 0, mpaint); Canvas.save ();// Save Canvas.scale (5f, 5f); Canvas.restore ();//Restore Canvas.drawbitmap (BITMAP2, +, mpaint); Super.ondraw (canvas);}}
The effect is as follows:
This is not the effect of the contrast is obvious.
A brief description of the two differences:
1. after drawing the BMP1 in the first code, the scaling operation is performed, and there is no saved state! Immediately after painting the BMP2, then BMP2 will also be affected by the scale!!
2. in the second paragraph of the code we do the canvas scaling before saving the canvas state, do the zoom operation and then remove the previously saved state, this is to ensure that the BMP2 normal drawing is not affected by the zoom!
Well, it seems to be understood, I do not know you understand it
Use of Canvas.save () and Canvas.restore () in Android