Android based tutorial: 8.3.16 Canvas API (Part 1)

label CanvasSaveRestoreLayerlayer
6219 people read comment(4) Collection report

Android based tutorial: 8.3.16 Canvas API (Part 1)

Tags (space separation): Android basic tutorial

Introduction to this section:

In front of us spent 13 sections to explain in detail the Paint Android class most commonly used API, this section begins to explain
Canvas (board) of some commonly used API in the USAndroid based tutorial 8.3.1 three drawing tools.
We have listed some of the ways in which we can call:

  • DrawXxx method familyA certain coordinate value in the current drawing area to draw, the other layer will be superimposed,
    That the painting behind the layer will cover the previous painting layer.
  • ClipXXX method familyIn the current drawing area (clip) out of a new drawing area, this
    The drawing area is the current drawing area of the canvas object. For example: clipRect (Rect new) (),
    Then the rectangle area is the current drawing area of canvas.
  • GetXxx method family: get some values related to Canvas, such as the width of the screen, the screen density, etc..
  • Save(),Restore(),SaveLayer(),RestoreToCountMethod for preserving and restoring layer
  • Translate(translation),Scale(zoom),Rotate(rotation),Skew(tilt)

Of course, there are other scattered methods, well, from the beginning of this section I will pick some of the sense of the meaning of the API to learn.
And this section is the first to bring to youTranslate(translation),Scale(zoom),Rotate(rotation),Skew(tilt)
as well asSave(),Restore(detailed)!
Official API document:Canvas
In addition, we must first clear the direction of the X axis and the Y axis in Canvas:

1.translate (translation)

method:Translate(DX float, Dy float)
analysisTranslation, the canvasCoordinate originTo the left and right direction of the mobile x, up and down the direction of the mobile y, canvas default location (0,0)
parameterDX for horizontal direction of the moving distance, Dy for the vertical direction of the moving distance

Use example:

        For(intI=Zero;I<Five;I+ +){
Canvas.drawCircle (Fifty,Fifty,FiftyMPaint);
Canvas.translate (One hundred,One hundred);

Operation effect:

2.rotate (rotation)

method:Rotate(degrees float) / ()Rotate(degrees float, PX float, py float)
analysisRotate degrees degrees around the origin of the coordinate, and the value is clockwise.
parameter: degrees for the rotation angle, PX and py to specify the rotation of the center point coordinates (PX, py)

Use example:

Rect Rect = Rect new (Fifty,Zero,One hundred and fifty,Fifty);
        Canvas.translate (Two hundred,Two hundred);
        For(Int= IZeroI; "Thirty-six{i++);
            Canvas.drawRect (rect, mPaint);

Operation effect:

Code analysis:

Here we call the translate (200200) to canvas the origin of the coordinates to the (200200), and then draw, so we
Draw results can be displayed on the canvas, if we are set up for the rotate (10200200), it will be such a

There is a question, this involves the concept of Canvas multi layer, and so will speak ~

3.scale (zoom)

method:Scale(SX float, sy float) /Scale(SX float, sy, PX float, py float, float)
analysisZoom on canvas
parameterSX for horizontal direction scaling, sy for the vertical scaling of the scaling, PX and py I do not know,Decimal to shrink,
Integer to enlarge

Use example:

        Canvas.drawBitmap (bmp,Zero,ZeroMPaint);
        Canvas.Scale(Zero point eightF,Zero point eightF);
        Canvas.drawBitmap (bmp,Zero,ZeroMPaint);
        Canvas.Scale(Zero point eightF,Zero point eightF);
        Canvas.drawBitmap (bmp,Zero,ZeroMPaint);

Operation effect:

4.skew (tilt)

method:Skew(SX float, sy float)
analysisIt can be translated as: oblique, oblique, twisted
parameter: SX for the X axis direction of the tilt of the corresponding angle, y for the sy axis direction of the tilt angle, the two values are tan value oh!
Are tan values! Are tan values! For example, to tilt 60 degrees in the X direction, so small values: Tan 60 = 3 = 1.732 sqrt!

Use example:

Canvas.translate(Two hundred,Two hundred);
Canvas.skew(Zero point twoF, -Zero point eightF);

Operation effect:

The concept of 5.Canvas layer and save () and restore ().

We usually call for love Canvas canvas, children's shoes have always felt that Canvas is a simple paper, so I want to
Q: how to use canvas to complete the next layer of animation? Above that translate translation example, why
DrawCircle (50, 50, 50, mPaint); the reference coordinates have been (50,50) that why there will be such an effect?
There are doubts children may have been confusing concepts with the Canvas screen, let us restore
Call translate the scene of the crime:

Figure, is the canvas coordinates of each point in the X, Y axis mobile 100; then if we want to return to (0,0)
Draw a new picture at the point? How to break, translate (-100, -100) slowly move back? Not really so
Tangled bar...

Well, not me, we can do translation before the current canvas state of preservation, in fact Canvas
We provide a layer (Layer) support, and these Layer (layer) is based on the "stack structure" to carry out the management of the

When we call(save)Method will save the state of the current Canvas and then as a Layer (layer), add to the Canvas stack,
In addition, the Layer (layer) is not a specific class, it is a conceptual thing!
And when we callRestore ()Method, will restore the state of the Canvas before, and at this time the layer stack Canvas
Will pop up the top of the stack Layer, the successor of the Layer came to the top of the stack, at this time of the Canvas back to the top of the stack to save the Canvas state!
Simply say is **:save () to the stack into a Layer, restore () pop top of a Layer, the Layer represents Canvas
State!That can be save () many times, can also be restore () many times, but the number of calls restoreCan not be greater than **save
Otherwise it will cause a mistake! This is most of the online statement, but the actual test did not appear such a problem, even if I restore
More than save, there is no error ~ visual system changed, as measured for everyone to see.

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

Write an example:

Example code: ();/ / save the current state of canvas

        Canvas.translate (One hundred,One hundred);
        Canvas.drawCircle (Fifty,Fifty,FiftyMPaint);

        Canvas.restore ();The preservation of the status of the Canvas / / recovery
        Canvas.drawCircle (Fifty,Fifty,FiftyMPaint);

Operation result:

Do not say what, the code and the results have been explained everything, and then we make a complex point, a hair
Multiple save () and restore ()!

Example code: ();

        Canvas.translate (Three hundred,Three hundred);
        Canvas.drawBitmap (bmp,Zero,ZeroMPaint); ();

        Canvas.drawBitmap (bmp,Zero,ZeroMPaint); ();

        Canvas.drawBitmap (bmp,Zero,ZeroMPaint); ();

        Canvas.translate (Zero,Two hundred);
        Canvas.drawBitmap (bmp,Zero,ZeroMPaint);

Operation result:

Result analysis:

First translation (300300) drawing, and then rotate 45 degrees drawing, then rotate 45 degrees drawing, and then translation (0200),
The period before each drawing is save (), see here you may have a question, and finally this translation is not y mobile 200
Why, how to turn left? Hey hey, I will tell you that rotate () rotation is the whole axis of the axis? Coordinate axes

Well, rotate () understand it, that's OK, then we try to restore ~ in front of us in the final drawing
Add two restore ()!

Canvas.translate(Zero,Two hundred);

Operation result:

Do not say what their own experience, and then add aRestore ()!

A little mean, come again, continue to addRestore ()

Well, it doesn't seem to be able to write any more.RestoreYes, because we only save four times, according to the online statement,
This is going to be wrong, is that true? Here we call Canvas to give us an access to the current stack
How many Layer methods:GetSaveCount ()And then both in save () and restore ().
Add a Log to print out the number of layers in the Layer stack:

The result is really popular, after practice, it may be Canvas, or for other reasons, here
To see the source to know, the time relationship, here we know that the number of restore can be more than save,
However, it is recommended that the number of restore or less than save, in order to avoid unnecessary problems.
As for the process of the stack into the stack and I will not say, I started painting, very easy to understand!

6.saveLayer () and restoreToCount () to explain

In fact, these two methods and save and restore are similar, but in the latter on the basis of some more stuff,
For example, saveLayer (), there are more than one of the following overloaded methods:

You can understand that(save)Method is to save theWhole Canvas, and saveLayer () can selectively save the state of a certain area,
In addition, we saw the meal places and there is a:SaveFlags int, this is set to save the object! Optional value:

sign explain
ALL_SAVE_FLAG Save all state
CLIP_SAVE_FLAG Save the state of a certain area of the clipping
CLIP_TO_LAYER_SAVE_FLAG Save the state in a pre - set range
FULL_COLOR_LAYER_SAVE_FLAG Preserve color coating
MATRIX_SAVE_FLAG The state preservation of Matrix information (translate, rotate, scale, skew)

PS: This is a bit of a problem, the low level of English, could be wrong, if there is to know, please. Put forward, thank you ~
Here we write an example to verify that we chooseCLIP_TO_LAYER_SAVE_FLAGMode to write an example

Implementation code:

Bounds RectF = RectF new (Zero,Zero,Four hundred,Four hundred);
Canvas.saveLayer(bounds, mPaint, Canvas.CLIP_TO_LAYER_SAVE_FLAG);
Canvas.drawColor(getResources) ().getColor(R.color.moss_tide);
Canvas.drawBitmap(bmp,Two hundred,Two hundredMPaint);
Canvas.drawBitmap(bmp,Three hundred,Two hundredMPaint);

Operation result:

(saveLayer) on the back again ~ detailed study used here to know about.

And then to thisRestoreToCount (int), this is more simple, direct incoming to restore to the Layer layer,
Jump directly to the corresponding layer, while the layer above all the Layer kicked out the stack, so that the layer
Become the top of the stack! Compared to you to write more than restore () more convenient and more convenient

7 code examples download:

Well, the code is written test, but also not much meaning, but may be the reader or want to paste the link bar!
Maybe you want the picture! Haha ~

Summary of this section:

This section is tangled up a few days to write out, because the author is not very clear at the beginning of the concept of the Canvas layer,
Today afternoon to do his thinking over his night, plus overtime finally put this thing to write out, believe to be able to help
We more clearly understand the Canvas, advanced custom control is not a ~ hey hey, this day is here,
If you have the wrong place welcome, thank you very much.

Android of Canvas group was also the last -! - Basic - painted

step on
Guess you're looking for
View comments
* the above user comments only represent their personal views, does not represent the views or position of the CSDN website
    personal data
    • visit611495 times
    • Integral:Eight thousand four hundred and ninety-seven
    • Grade
    • Rank:1221st name
    • original211
    • Reproduced:4
    • Translation:0
    • Comments:623
    Blog column