Custom View Drawing Chapter (vi): Canvas Those transformations you should know

Source: Internet
Author: User
Tags translate function

Come in my arms.
Or
Let me live in your heart

                                            一仓央嘉措
First, what is canvas?

What is canvas? This is how the official documentation is presented:

the Canvas class holds The The  draw calls. To draw something, need 4  basic components:a Bitmap to  hold the  pixels, a  Canvas to  host the  Draw calls (writing  into  the  bitmap), a  drawing Primitive ( e.g. Rect,path, text , Bitmap), and  a  paint (to  describe the  colors and  styles for  the  Drawing).  

The Canvas class is for drawing, and you need 4 basic elements to draw a graphic:

    • Where to draw. Draw on the bitmap. (equivalent to paper, we put the picture on the paper)

    • How to draw. (Call canvas to perform the drawing operation.) such as Canvas.drawcircle (), Canvas.drawline (), Canvas.drawpath () draw the image we need. )

    • The content of the painting. (for example, I want to draw a flower on paper, draw a circle according to my own needs, draw a straight line, draw a path, etc.)

    • with what painting. (Draw a flower on paper, it must be painted with a pen, the pen here refers to paint)

Canvas Canvas is infinitely large, and it has no boundaries. How to understand this sentence? For example: The canvas is the view outside the window, and the phone screen is the window, you see the window in the windows of the scenery is limited. I can also draw the graphic outside the screen, through the transformation and operation of the Canvas, so that the outside of the screen graphics display inside the screen.

Second, Canvas drawing

Canvas to draw some common graphs:

Mpaint. SetColor(Color. RED);Draw a line canvas. DrawLine( -, -, -, -, Mpaint);Draw a rectangular canvas. DrawRect( -, $, -, -, Mpaint);Draw the Road Jin Mpaint. Settextsize( -);Mpaint. Setstrokewidth(2);Mpaint. SetStyle(Paint. Style. FILL);Canvas. DrawText("I am a stone.", -, -, Mpaint);

Third, the transformation and operation of the Canvas

Sometimes we also need to do some work on Canvas, such as rotation, cropping, panning, and so on.

    • Canvas.translate panning

    • Canvas.rotate rotation

    • Canvas.scale Scaling

    • Canvas.skew wrong cut

    • Canvas.cliprect cropping

    • Canvas.save and Canvas.restore Preservation and recovery

    • Porterduffxfermode image Blending (paint correlation method)

Yo also, let's have a look next to each other.

1, (PAN) translate

Canvas.translate () method is used to achieve the canvas translation, the original canvas is the upper left corner as the origin, right is the x-axis positive direction, downward is the y-axis positive direction, I believe we are very familiar with.

Method preview:

translate(floatfloat dy)

Parameter meaning:

FLOAT DX: The distance of the horizontal translation, the amount of positive direction (right) translation, negative number pointing to the negative direction (left) translation
Flaot dy: The distance in the vertical direction, the positive direction (down) of the shift, negative number pointing to the negative direction (up) the amount of translation

In this code, the same circle is drawn once before the canvas is panned, and then once again, what do you think the result will be?

 Mpaint.setColor  ( Color)  Canvas.drawcircle  (200 ,        200 , 200 , Mpaint) ;  Mpaint.setcolor  (Color)  Canvas.translate  (200 , 200 )         Canvas.drawcircle  (200 , 200 , 200 , Mpaint) ;  

Do you think the final is not a 2-circle coincidence:

The actual effect is this:

The eggs are all broken, why does the red box not move?

Quote 启航 from the great God:

这是由于屏幕显示与Canvas根本不是一个概念!Canvas是一个很虚幻的概念,相当于一个透明图层(用过PS的同学应该都知道),每次Canvas画图时(即调用Draw系列函数),都会产生一个透明图层,然后在这个图层上画图,画完之后覆盖在屏幕上显示。

The translate function actually corresponds to the translation coordinate system, that is, the position of the origin of the translation coordinate system.

2. Rotation (Rotate)

Rotate the canvas to look a little similar to the picture rotation effect. The default is to rotate around the origin of the coordinate system, or you can set the center point rotation.

Method preview:

rotate(floatdegrees)rotate(floatdegreesfloatfloat py)

The first constructor degrees parameter represents the degree of rotation. A positive number indicates a clockwise rotation, a negative number indicates counterclockwise rotation, and a 0 degree indicates the horizontal x-axis direction. The default is the coordinate origin as the center point.

The second constructor is PX, and the PY represents the center point coordinates.

Then let's look at an example:

Mpaint. SetColor(Color. RED);Non-rotated straight line canvas. DrawLine( $, $, -, $, Mpaint);Rotate Clockwise -Degree Canvas. Rotate( -);Mpaint. SetColor(Color. GREEN);Canvas. DrawLine( $, $, -, $, Mpaint);

Here is an example of the first constructor, which first draws a red, non-rotated line, rotates the canvas 30 degrees clockwise, and then draws the rotated green line.

Note: The difference between rotating the canvas and the picture rotation.

Zoom 3, put (scale)

Canvas scaling, there are also 2 construction methods. Method preview:

scale(floatfloat sy)scale(floatfloatfloatfloat py)

The first constructor, the parameter sx, represents a horizontal scale, greater than 1 for magnification, and less than 1 for shrinking. For example, the horizontal direction is 100 px, the scale is 1.5f, then the actual pixel is 100*1.5=150px. The parameter Sy represents the scale of the vertical direction.

The second method source code is as follows:

 /** * Preconcat the current matrix WI     Th the specified scale. * * @param  SX The amount to scale in X * @param  sy The amount to scale in Y * @param  px The X-coord for the pivot point (  Unchanged by the scale) * @param  PY-the Y-coord for the pivot point (unchanged by The scale) */ public  final  void  scale  (float  SX, Span class= "Hljs-keyword" >float  sy, float  px,         float  py) {translate (px, py);        Scale (SX, SY);    Translate (-px,-py); }

The PX and py are scaled datum points, and the difference between the scale (float SX, float sy) can be seen very clearly from the source code:

translate(px, py);scale(sx, sy);translate(-px, -py);

Pan the canvas px,py first, then scale,scale the canvas back to the original Datum point after the end.

Specifically, let's take a look at the following example:

Canvas. Save();Mpaint. SetColor(Color. RED);Non-scaled round canvas. Drawcircle( $, $, -, Mpaint);Canvas to zoom to canvas. scale(1.5F1.5F;Mpaint. SetColor(Color. GREEN);Canvas. Drawcircle( $, $, -, Mpaint);Canvas. Restore();Canvas. scale(1.5F1.5F $, $);Mpaint. SetColor(Color. YELLOW);Canvas. Drawcircle( $, $, -, Mpaint);

Save,restore is explained later in this article for saving and restoring the canvas. The red circle is the non-scaled canvas, the green is 1.5 times times the circle, and the yellow is the circle that translates (200,200) and then zooms back 1.5 times times again ( -200,-200).

4, the wrong cut (skew)

Preview of the canvas Warp method:

skew(floatfloat sy)

Parameters:

Float SX: Tilt the canvas in the x direction at the appropriate angle, the tan value of the SX tilt angle
Float SY: Tilt the canvas in the y direction to the corresponding angle, SY is the tan value of the tilt angle

In the following example, I tilt the rectangle 30 degrees in the x direction, and the tan30=1/√3 is approximately equal to 0.56.

Mpaint. SetColor(Color. RED);Round canvas, not rotated. DrawRect( -, -, -, -, Mpaint);Canvas. Skew(0.56F0F;Mpaint. SetColor(Color. GREEN);Canvas. DrawRect( -, -, -, -, Mpaint);

It can be seen from the perspective that we set the X-direction tilt, instead of the Y-direction, which is why it is called the wrong cut. There must be doubt in your heart? How do you calculate the coordinates of each point? Let's analyze the following together:

canvas.drawRect(100100500400, mPaint);

A (100,100), B (500,100), C (500,400), D (100,400) Set the canvas x-direction tilt 0.56f,y direction unchanged.

The value of the horizontal axis of a point is the horizontal axis of the +a point of a point. * Tilt Value
The value of the B-point horizontal slope is the horizontal axis of the +a point of the B-point * tilt value
C Point the horizontal axis of the value is the C point of the horizontal axis + rectangle width * Tilt value
D Point horizontal axis tilt value is D point horizontal axis + Rectangle width * Tilt value

5. Crop canvas (Clip series functions)

The crop canvas uses the Clip series function to get the latest canvas shape (the default intersection) by taking the intersection of Rect, Path, region, and poor set operations. In addition to calling save, the restore function, this operation is irreversible, the canvas canvas is cropped, it can no longer be restored.

Clip Series function Method preview:

    • ClipRect (RECTF Rect, op op)

    • ClipRect (Rect rect, op op)

    • ClipRect (RECTF rect)

    • ClipRect (rect rect)

    • ClipRect (float left, float top, float right, float bottom, op op)

    • ClipRect (float left, float top, float right, float bottom)

    • ClipRect (int left, int top, int. right, int bottom)

    • Clippath (Path Path, op op)

    • Clippath (path Path)

    • Clipregion (Region, op op)

    • Clipregion (region)

The cutting function is not very difficult to use in Doha. Let's look at a simple example:

 canvas.drawColor(Color.GREEN); canvas.clipRect(new Rect(200200500400), Region.Op.DIFFERENCE); canvas.drawColor(Color.YELLOW);

First paint the canvas background green, and then cut the rectangle, here is the difference set (Region.Op.DIFFERENCE), the classmate with the PS will know to take the reverse of the selected area.

6, Save and Restore (save (), restore ())

Panning, rotating, zooming, trimming, cropping are irreversible, and what if we still need to return to the original state to manipulate the canvas? The careful classmate must know that save (), the Restore () method has already appeared above, right, it is used to save and restore the canvas state, so that we can happily reversible operation.

Method preview:

Save (): Each time the Save () function is called, the state of the current canvas is saved and placed in a specific stack;
Restore (): Whenever the Restore () function is called, the top-most canvas state of the stack is taken out and the current canvas is restored in this state and the canvas is drawn.

To see a simple example, first paint the entire canvas green, then save the canvas, then crop the rectangle, paint the cropped canvas yellow, then restore the canvas, and paint the canvas red:

 Canvas.drawColor  ( Color)         Save current canvas Canvas.save  ()  Canvas.cliprect  (New Rect (200 , 200 , 500 , 400 ))  Canvas.drawcolor  (Color) ;  Restore canvas Canvas.restore  ()  Canvas.drawcolor  (Color)   

The stage diagram is shown below, culminating in full-screen red:

Note: It is best to pair when using Canvas.save and Canvas.restore, which can cause an exception if restore () has more calls than save ().

7. Image Blending (Porterduffxfermode)

The constructor for Porterduffxfermode image blending is as follows:

publicPorterDuffXfermode(PorterDuff.Mode mode)  

The parameter Porterduff.mode represents a blending mode with 18 enumeration values.

Custom View's Drawing chapter (v): Circular water waves, has a preliminary introduction to the mix of graphics, I will not repeat the writing here.

We often use this feature in project development: to display rounded pictures. Let's see how it's implemented:

    /** * @param Bitmap original * @param pixels fillet size * @return  */     PublicBitmapGetroundcornerbitmap(Bitmap Bitmap,floatPixels) {//Get bitmap's wide height        intwidth = Bitmap.getwidth ();intHeight = bitmap.getheight ();        Bitmap Cornerbitmap = bitmap.createbitmap (width, height, Bitmap.Config.ARGB_8888); Paint paint =NewPaint (); Canvas Canvas =NewCanvas (CORNERBITMAP); Paint.setantialias (true); Canvas.drawroundrect (NewRECTF (0,0, width, height), pixels, pixels, paint); Paint.setxfermode (NewPorterduffxfermode (PorterDuff.Mode.SRC_IN)); Canvas.drawbitmap (Bitmap,NULL,NewRECTF (0,0, width, height), paint);//Draw BorderPaint.setstyle (Paint.Style.STROKE); Paint.setstrokewidth (6);        Paint.setcolor (Color.green); Canvas.drawroundrect (NewRECTF (0,0, width, height), pixels, pixels, paint);returnCornerbitmap; }

1, first through the Bitmap cornerBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); generation of cornerBitmap instances, note that Bitmap only through static methods to obtain its instance, and can not be directly new out.

2. Draw rounded rectangles canvas.drawRoundRect(new RectF(0, 0, width, height), pixels, pixels, paint); .

3, for the Paint setting PorterDuffXfermode . Parameter PorterDuff.Mode.SRC_IN intersection.

4, draw the original image.canvas.drawBitmap(bitmap, null, new RectF(0, 0, width, height), paint);

5. Draw the rounded corners of the border.canvas.drawRoundRect(new RectF(0, 0, width, height), pixels, pixels, paint);

The simple 13-line code implements the rounded border effect.

Canvas related knowledge, it is here, if this article has helped you, remember to add attention to Oh .

Please follow GitHub

Custom View Drawing Chapter (vi): Canvas Those transformations you should know

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.