The Ondraw () method of overriding view is often encountered when you define a control, and the Ondraw () method is often designed to save () and restore (). These two matches appear to be used to preserve the state of the canvas and remove the saved state.
Detailed functions such as the following:
1.save (): Used to save the state of the canvas ,the code after theSave () method , can call the canvas pan, zoom, rotate, crop and so on!
2.restore (): Used to restore The state saved before the canvas, preventing the Save () method code from following the canvas Run the operation. Continue to have an impact on the likely drawing. This method can avoid the influence of the joint!
Here's a quick example. Let's take a look at 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);}}
A very easy Demo example is to draw two pictures, and after the first one is finished. Magnified the canvas by 5 times times. What the effect sees:
watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmdm1ode2oa==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">
Below, we change the code slightly, such as the following:
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);}}
Effects such as the following:
This is not the effect of the contrast is very obvious.
A brief description of the two differences:
1. The first paragraph of the code BMP1 after the operation of the zoom operation, and there is no saved state! Immediately after the BMP2 was drawn. Then BMP2 will also be affected by scaling.
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