Android Basics Getting Started tutorial--8.3.16 Canvas API details (Part 1)

Source: Internet
Author: User


Android Basics Getting Started tutorial--8.3.16 Canvas API details (Part 1)


tags (space delimited): Android Basics Getting Started Tutorial


Introduction to this section:


We've spent 13 of bars explaining the most common APIs for the paint class in Android, and we'll start with this section.
Canvas (artboard) Some of the common API, we start in the Android basic tutorial--8.3.1 three drawing Tools class
We have listed some of the methods we can call, and we divide the class:


    • Drawxxx Method Family : Draw in the current drawing area with a certain coordinate value, and the layer will overlay,
      That is, the layers that you paint later overwrite the layers that you painted earlier.
    • Clipxxx Method Family : Crop (clip) out a new paint area in the current paint area, this
      The paint area is the current drawing area of the canvas object. For example: ClipRect (New Rect ()),
      Then the rectangular area is the canvas's current paint area.
    • GetXXX method Families : Get some values related to canvas, such as width, height, screen density, and so on.
    • Save (),Restore (),Savelayer(),restoretocount() Save the Recovery layer method
    • Translate (PAN),Scale (zoom),rotate(rotation),skew(tilt)


Of course there are other scattered methods, well, starting from this section I will pick some interesting API to learn ~
This section first brings you translate(PAN), scale (zoom),rotate(rotation),skew(tilt)
And the explanation of save(),restore()!
Official API Documentation: Canvas
In addition, we need to clarify the direction of the X and y axes in the canvas:





1.translate (PAN)

method :translate(float dx, float dy)
parsing : panning, moving the coordinate origin of the canvas to the left and right direction X, moving up and down Y,canvas the default position (0,0)
parameters : DX is the horizontal direction of movement distance, DY is the vertical direction of the moving distance


Examples of Use :

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

2.rotate
Method: rotate (float degrees) / rotate (float degrees, float px, float py)
Analysis: rotate degrees degrees around the origin of the coordinate, the value is positive clockwise
Parameters: degrees is the rotation angle, px and py are the coordinates of the center point of the specified rotation (px, py)

Examples of use:

        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 result:

Code analysis:

Here we first call translate (200,200) to move the origin of the canvas to (200,200), and then draw, so we
The result of drawing can be displayed on the canvas completely. If we set (10,200,200) for rotate, it will be such a
result:

Do you have any questions? This concept involves multiple layers of 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, I do n’t know about px and py, the decimal is to reduce
The integer is the magnification

Examples of use:

        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 result:

4.skew (tilt)
Method: skew (float sx, float sy)
Analysis: inclined, can also be translated as bevel, twisted
Parameters: sx is the corresponding angle of tilt in the x-axis direction, sy is the corresponding angle of tilt in the y-axis direction, both values are tan values!
It ’s all tan! It ’s all tan! For example, if you want to tilt 60 degrees in the x-axis direction, then the small value corresponds to: tan 60 = radical 3 = 1.732!

Examples of use:

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

5. The concept of Canvas layer and detailed explanation of save () and restore ()
We generally like to call Canvas a canvas. Children's shoes always think that Canvas is a simple drawing paper, so I think
Ask how multi-layer animation is done with canvas? The translate example above, why
drawCircle (50, 50, 50, mPaint); The reference coordinate is always (50,50). Why does this effect occur?
The doubtful children's shoes may have been confusing the concept of the screen with the concept of Canvas. Let's restore it below
The scene of the call to translate:

, Is the origin of the canvas coordinates each time move 100 on the x, y axis; then if we want to go back to (0,0)
Draw a new figure at the point? How to break, translate (-100, -100) slowly translate back? Not really like this
Tangle it ...

Okay, do n’t sell it anymore, we can save the current state of the canvas before doing the translation transformation. In fact, Canvas is
We provide support for layers, and these layers are managed according to the "stack structure"

When we call the save () method, the current state of the Canvas will be saved and then added to the Canvas stack as a Layer,
In addition, this Layer is not a specific class, but a conceptual thing!
When we call the restore () method, the state of the previous Canvas will be restored, and at this time the layer stack of the Canvas
The Layer at the top of the stack will pop up, and the subsequent Layer will come to the top of the stack, and the Canvas at this time will return to the Canvas state saved at the top of the stack!
Simply put: **: save () pushes a Layer onto the stack, and restore () pops up a Layer on top of the stack.
status! In other words, you can save () multiple times and restore () multiple times, but the number of restore calls cannot be greater than ** save
Otherwise it will cause an error! This is the majority of the statement on the Internet, but there is no such problem in the actual test, even if I restore
There are more times than save, and there are no errors. The visual observation is that the system has changed. Wait for the next test to show everyone ~

Come and write an example to verify the role of save and restore!

Write an example:

Example code:

        canvas.save (); // Save the current canvas state

        canvas.translate (100, 100);
        canvas.drawCircle (50, 50, 50, mPaint);

        canvas.restore (); // Restore the saved Canvas state
        canvas.drawCircle (50, 50, 50, mPaint);
operation result:

Needless to say, the code and results have explained everything, and then we made it a bit more complicated
Multiple save () and restore ()!

Example 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);
operation result:

Result analysis:

First translate (300,300) to draw, then rotate 45 degrees to draw, then rotate 45 degrees to draw, then translate (0,200),
Save () before drawing each time during the period, you may have a question when you see here, the last translation is not y movement 200
So, how did it turn to the left? Hey, will I tell you that rotate () rotates the entire coordinate axis? Coordinate axis
Variety:

Well, rotate () got it, right, then let's try restore ~ we are in front of the final drawing
Add two restore ()!

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

Don't say anything, feel for yourself, and add multiple restore ()!

Somewhat interesting, come again, continue to add restore ()

Well, it seems that we can't write restore anymore, right, because we only saved four times, according to the online saying,
This will be wrong, is it true? Here we call the one provided by Canvas to get the current stack
How many Layer methods are there: getSaveCount (); then before and after save () and restore ()
Add a Log to print the number of Layer layers in the stack:

The result is really good news, after all, the real knowledge is practiced, maybe the Canvas has changed, or other reasons, here
It depends on the source code, time relationship, here we know that the number of restores can be better than save,
However, it is still recommended that the number of restores is still less than save to avoid unnecessary problems ~
As for the process of stacking and unstacking, I will not say anything. The author draws his own strokes, which is very easy to understand!

6.saveLayer () and restoreToCount () explain
In fact, these two methods are similar to save and restore, but there are more things on the basis of the latter.
For example saveLayer (), there are several overloaded methods:

You can understand that save () method saves the entire Canvas, and saveLayer () can selectively save the state of a certain area,
In addition, we see that there is an int saveFlags in the accommodation, and this is set to save the object! Available values are:

Mark Description
ALL_SAVE_FLAG save all states
CLIP_SAVE_FLAG saves the status of a cropped area
CLIP_TO_LAYER_SAVE_FLAG save the state in the preset range
FULL_COLOR_LAYER_SAVE_FLAG save color coating
HAS_ALPHA_LAYER_SAVE_FLAG opaque layer save
MATRIX_SAVE_FLAG Matrix information (translate, rotate, scale, skew) state saving
PS: The above instructions are a bit problematic. I have a low level of English and may be wrong. If you know anything, please correct me.
Here we write an example to verify: we use CLIP_TO_LAYER_SAVE_FLAG mode 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);
operation result:

Regarding saveLayer (), I will use it in detail later ~ Let me know about it ~

Then go to this restoreToCount (int), which is simpler, directly pass in the Layer layer to be restored to,
Jump directly to the corresponding layer, and at the same time, all Layer above the layer will be kicked out of the stack, let the layer
Become the top of the stack ~! It's much easier and faster than writing multiple restore () ~

7. Download code samples in this section:
Well, the code is written for testing, and it does n’t make much sense to come, but maybe the reader still wants it, just post the link!
Code download: CanvasDemo.zip
Maybe you want this picture! Haha ~
Summary of this section:
This section was written after a few days of entanglement, because the concept of the Canvas layer was not very clear at the beginning.
After finishing the work this afternoon, I thought about it, and I worked overtime at night to finally write this thing out. I believe it should help
Everyone understands Canvas more clearly, and you wo n’t be confused when you advanced custom controls ~ Hey, this section is here,
If there is something wrong, welcome to submit it, thank you very much ~

references:
Android の Canvas を 使 い こ な す! – Basic drawing

Copyright statement: This article is an original article by bloggers and may not be reproduced without the permission of the bloggers.

Basic Android Tutorial-8.3.16 Canvas Detailed API (Part 1)

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.