I. First, let's talk about the SAVE and restore functions of canvas. This is a very attractive part of canvas.
The 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 that the SAVE and restore methods are called. What are they used?
Saved save: used to save the canvas status. After saving, you can call operations such as pan, zoom, rotate, miscut, and crop of the canvas.
Restore restore: used to restore the State saved before the canvas. This prevents operations performed on the canvas after the save operation from affecting subsequent painting.
Save and restore must be used together (Restore can be less than save, but not more). If the restore calls more than save, an error is thrown. The SAVE and restore operations on canvas are often mixed.
For example, we first want to draw a right arrow in the canvas. Of course, we can draw it directly. In addition, we can also rotate the canvas 90 ° and draw an up arrow first, and then rotate back (this rotation operation is very useful for marking on the circumference ). Then, if we want to have a 20-pixel circle in the lower right corner, 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 (90, PX/2, Py/2 );
// Note that the rotate must be followed by getmeasuredwidth () and getmeasuredheight ()... Why is it unclear ..
// 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, 10, linepaint );
Result 1:
Figure 1
What will it look like if we don't call save and restore? 2:
Figure 2
From the two graphs, we can see the obvious difference in the circle position. Without the SAVE and restore operations on the canvas, all images are drawn on the canvas after 90 ° rotation. After the ondraw method is executed, the canvas is automatically restored. When the SAVE and restore operations are executed differently, the drawing may be different.
Therefore, the special operations on the canvas are often mixed between SAVE and restore.
Ii. Next, let's talk about the translate method.
Like the usage of j2's translate, the function is to move the origin. The default origin () is in the upper left corner of the screen. You can use translate (x, y) to set the position (x, y) as the origin. |