When you create a new control or modify an existing control, we all involve overriding the control or View of the OnDraw method.
OnDraw method will pass in a Canvas object, which is the canvas you use to draw the visual interface of the control.
in the OnDraw method, we often see the call Save and the Restore method, what exactly are they used for?
save : Used to save canvas Span lang= "ZH-CN" style= "line-height:1.5; The state of Font-family:simsun ". save canvas translation, retraction, rotation, error cutting, cropping, and other operations.
? Restore : Used to restore Canvas the previously saved state. Preventing The actions that are performed on the Canvas after save has an impact on subsequent drawing.
Saveand theRestoreto pair with (Restorecan be comparedSaveless, but not much), ifRestorenumber of calls thanSavemore, will causeError.
For example, we would like to draw a right-pointing triangular arrow on the canvas, of course, we can draw directly, and we can also rotate the canvas first - °, draw an upward arrow, and then rotate it back (this rotation is useful for marking marks on the circumference of the drawing). Then, we want to have a three - Pixel circlein the lower-right corner, so the core code in OnDraw is:
int px = Getmeasuredwidth ();
int py = Getmeasuredwidth ();
Draw background
Canvas.drawrect (0, 0, px, py, backgroundpaint);
Canvas.save ();
Canvas.rotate (PX/2, PY/2);
Draw Up ARROW
Canvas.drawline (PX/2, 0, 0, PY/2, linepaint);
Canvas.drawline (PX/2, 0, px, PY/2, linepaint);
Canvas.drawline (PX/2, 0, PX/2, py, linepaint);
Canvas.restore ();
Draw Circle
Canvas.drawcircle (px-10, py-10, ten, linepaint);
effect 1 as shown:
Figure 1
if we don't call Save and the Restore What would it be like? 2 is shown below:
Figure 2
from these two graphs, we can see the obvious difference in the position of the circle. Do not proceedCanvasof theSaveand theRestoreoperation, all the images are rotated in the canvas . -° After the drawing on the canvas. When the execution finishesOnDrawmethod, the system automatically restores the canvas back. Saveand theRestorewhen the operation is performed differently, it can cause the drawing to be different.
So, Save and the Restore between, often mingled with the Canvas of special operations.
Save and restore for canvas