Basic Android tutorial -- 8.3.16 Canvas API (Part 1)

Source: Internet
Author: User

Basic Android tutorial -- 8.3.16 Canvas API (Part 1)
Basic Android tutorial -- 8.3.16 Canvas API (Part 1)

Tags (separated by spaces): basic Android tutorial

This section introduces:

We have spent 13 sections to explain in detail most of the commonly used Paint APIs in Android.
Canvas APIs are commonly used. For details about the three plotting tools in the basic tutorial of Android-8.3.1
We have already listed some of the methods available for calling. We will divide them into the following classes:

DrawXxx method family: Draws a picture in the current drawing area with a certain coordinate value. In addition, the layers are superimposed,
That is, the layer after painting will overwrite the layer of the previous painting. ClipXXX method family: Crop (clip) A new drawing area in the current drawing area.
The drawing area is the current drawing area of the canvas object. For example, clipRect (new Rect ()),
The rectangle is the current drawing area of the canvas. GetXxx method family: Get some Canvas-related values, such as width and height and screen density. Save(), Restore(), SaveLayer(), RestoreToCount() And other methods for saving and restoring Layers Translate(Translation ), Scale(Scaling ), Rotate(Rotate ), Skew(Tilt)

Of course, there are other scattered methods. Well, from the beginning of this section, I will pick some APIs that seem to be interesting for learning ~
What I will bring to you in this section is:Translate(Translation ),Scale(Scaling ),Rotate(Rotate ),Skew(Tilt)
AndSave(),Restore() Details!
Official API documentation: Canvas
In addition, we must first specify the direction of the X and Y axes in the Canvas:

1. translate (Translation)

Method:Translate(Float dx, float dy)
Analysis: Translation: Move the canvasCoordinate OriginMove x to the left and right directions, and y to the bottom. The default position of canvas is (0, 0)
Parameters: Dx indicates the moving distance in the horizontal direction and dy indicates the moving distance in the vertical direction.

Example:

        for(int i=0; i < 5; i++) {            canvas.drawCircle(50, 50, 50, mPaint);            canvas.translate(100, 100);        }

Running Effect:

2. rotate)

Method:Rotate(Float degrees )/Rotate(Float degrees, float px, float py)
Analysis: Rotate the degree of degrees around the coordinate origin. The value is positive clockwise.
Parameters: Degrees is the rotation angle, px and py are the coordinates of the specified rotation center (px, py)

Example:

        Rect rect = new Rect(50,0,150,50);        canvas.translate(200, 200);        for(int i = 0; i < 36;i++){            canvas.rotate(10);            canvas.drawRect(rect, mPaint);        }

Running Effect:

Code Analysis:

Here, we first call translate (200,200) to move the coordinate origin of the canvas to (200,200) and then draw the canvas.
The drawn results can be completely displayed on the canvas. If we set (10,200,200) for rotate
Result:

If you have any questions, I will talk about the concept of multi-layer Canvas ~

3. scale)

Method:Scale(Float sx, float sy )/Scale(Float sx, float sy, float px, float py)
Analysis: Zoom the canvas
Parameters: Sx is the horizontal scaling ratio, sy is the vertical scaling ratio, px and py I do not know,Decimal point is reduced,
The integer is enlarged.

Example:

        canvas.drawBitmap(bmp,0,0,mPaint);        canvas.scale(0.8f, 0.8f);        canvas.drawBitmap(bmp, 0, 0, mPaint);        canvas.scale(0.8f, 0.8f);        canvas.drawBitmap(bmp,0,0,mPaint);

Running Effect:

4. skew (skew)

Method:Skew(Float sx, float sy)
Analysis: Skew. It can also be translated as oblique and distorted.
Parameters: Sx is the corresponding angle of the X axis and sy is the corresponding angle of the Y axis. The two values are tan values!
All are tan values! All are tan values! For example, if you want to tilt 60 degrees on the X axis, a small value corresponds to tan 60 = root 3 = 1.732!

Example:

        canvas.drawBitmap(bmp,0,0,mPaint);        canvas.translate(200, 200);        canvas.skew(0.2f,-0.8f);        canvas.drawBitmap(bmp,0,0,mPaint);

Running Effect:

5. Canvas layer concepts and save () and restore () Details

We generally like to call Canvas as a Canvas. Kids shoes always think Canvas is a simple Canvas. So I think
How can I use canvas to complete multi-layer animations? The above example of translate translation, why?
DrawCircle (50, 50, 50, mPaint); the reference coordinate is always (50, 50). Why is this effect?
The confused shoes may have been confusing the screen concept with the Canvas concept. Let's restore it.
Call the event site of translate:

It is the coordinate origin of the canvas that is moved 100 on the x and Y axes respectively each time. If we want to return to (0, 0)
What about creating a new image at the point? How can we break it down? translate (-100,-100) and translate it back slowly? That's not true.
Tangle...

Okay, we can save the current canvas status before performing the translation transformation. Actually, Canvas is
We provide Layer Support, and these layers are managed by "stack structure ".

When we callSave ()Method To save the status of the current Canvas and add it to the Canvas stack as a Layer,
In addition, this Layer is not a specific class, it is just a conceptual thing!
When we callRestore ()Method, the Canvas state is restored, and the Canvas layer Stack
The Layer at the top of the stack will pop up, and the subsequent Layer will come to the top of the stack. At this time, the Canvas will return to the Canvas state saved at the top of the stack!
Simply put, **: save () is pushed to the stack into a Layer. restore () is used to bring up a Layer at the top of the stack. This Layer represents
Status!That is to say, you can save () multiple times or restore () multiple times, but the number of restore callsCannot be greater than ** save
Otherwise, an error occurs! This is the majority of online statements, but this problem does not occur in actual tests, even if I restore
There are no errors because the number of times is more than save ~ The system has been changed for visual testing. You can see it later ~

Come and come, write an example to verify the functions of save and restore!

Write example:

Sample Code:

Canvas. save (); // save the status canvas of the current canvas. translate (100,100); canvas. drawCircle (50, 50, 50, mPaint); canvas. restore (); // restore the status Canvas of the saved canvas. drawCircle (50, 50, 50, mPaint );

Running result:

Needless to say, the code and results have already explained everything, and then we have to make it more complicated.
Multiple save () and restore ()!

Sample Code:

        canvas.save();        canvas.translate(300, 300);        canvas.drawBitmap(bmp, 0, 0, mPaint);        canvas.save();        canvas.rotate(45);        canvas.drawBitmap(bmp, 0, 0, mPaint);        canvas.save();        canvas.rotate(45);        canvas.drawBitmap(bmp, 0, 0, mPaint);        canvas.save();        canvas.translate(0, 200);        canvas.drawBitmap(bmp, 0, 0, mPaint);

Running result:

Result Analysis:

First translate (300,300), then rotate 45 degrees, then rotate 45 degrees, then translate (0,200 ),
Save () before drawing each time. You may have a question here. The final translation is not y moving 200.
Why is it left? Hey, will I tell you if rotate () is the entire axis rotated? Coordinate Axis
Changes:

Well, rotate () understands it, right? Let's try restore ~ Before the final drawing
Add two restores ()!

        canvas.restore();        canvas.restore();        canvas.translate(0, 200);        canvas.drawBitmap(bmp, 0, 0, mPaint);

Running result:

Don't talk about anything, just try again.Restore ()!

A little interesting. Come back and continue to addRestore ()

Well, it seems I can't write any more.RestoreYes, because we only save four times. According to the online saying,
This will report an error. Is it true? Here, we call a Canvas to provide us with a way to get the current stack.
How many layers are available:GetSaveCount (); Then both save () and restore ()
Add a Log to print the layers in the stack:

The result is really nice to hear. After all, it may be because Canvas has been changed, or for other reasons.
Only the source code can understand the time relationship. Here we know that restore times can be more than save,
However, it is recommended that the number of restore operations be less than the number of save operations to avoid unnecessary problems ~
As for the process of going into and out of the stack, I will not talk about it. I am very easy to understand!

6. saveLayer () and restoreToCount ()

In fact, these two methods are similar to the save and restore methods, but there are some additional things on the basis of the latter,
For example, saveLayer () has the following overload methods:

You can understand itSave ()The method isEntire CanvasWhile saveLayer () can selectively Save the status of a region,
In addition, we can see that there is a DDH and:Int saveFlags, This is set to save the object! Optional values:

Mark Description
ALL_SAVE_FLAG Save all statuses
CLIP_SAVE_FLAG Save the status of a cropped area
CLIP_TO_LAYER_SAVE_FLAG Save the status in the preset range
FULL_COLOR_LAYER_SAVE_FLAG Save COLOR COATING
HAS_ALPHA_LAYER_SAVE_FLAG Save opacity Layers
MATRIX_SAVE_FLAG Save the status of Matrix information (translate, rotate, scale, skew)

PS: the above description is a bit of a problem. I have a low level of English and may make a mistake. If you know, please correct me. Thank you ~
Here we will write an example to verify: we chooseCLIP_TO_LAYER_SAVE_FLAGMode to write an example

Implementation Code:

        RectF bounds = new RectF(0, 0, 400, 400);        canvas.saveLayer(bounds, mPaint, Canvas.CLIP_TO_LAYER_SAVE_FLAG);        canvas.drawColor(getResources().getColor(R.color.moss_tide));        canvas.drawBitmap(bmp, 200, 200, mPaint);        canvas.restoreToCount(1);        canvas.drawBitmap(bmp, 300, 200, mPaint);

Running result:

For more details about the use of saveLayer ~ Here is a rough idea ~

Next to thisRestoreToCount (int)This is simpler. You can directly input the layers to be restored,
Directly jump to the corresponding Layer, and all the layers above the Layer will be kicked out of the stack, so that the Layer
Become the top stack ~! It is much easier to write multiple restores () than you do ~

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.