Android uses canvas to draw various graphics and paint usages.

Source: Internet
Author: User
Tags drawtext

Citation: http://blog.csdn.net/carlfan/article/details/8139984

1, first say the canvas class:

Class Overview

The Canvas class holds the "draw" calls. To draw something, your 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).

This class is equivalent to a canvas, you can draw a lot of things inside;

We can think of this canvas as a piece of memory that the system provides to us (but actually it's just a drawing API, real memory is the bitmap), and it provides a whole set of methods for manipulating this memory area, all of which are drawing APIs. In this way we have been able to draw a stroke or use graphic to paint what we need, and to draw what we want to show is controlled by ourselves.

This approach can be divided into two types of environments: one is canvas drawing with normal view, and the other is drawing using a dedicated Surfaceview canvas. The main difference between the two is that you can define a dedicated thread in Surfaceview to do the drawing work, and the application does not need to wait for the view brush graph to improve performance. The previous one is suitable for small, low frame rate animation, such as chess games, and the latter is mainly used in the game, high-quality animation aspects of the drawing.

The following are common methods of the canvas class:

DrawRect (RECTF rect, paint paint)//plot area, parameter one for RECTF one area

DrawPath (path path, paint paint)//Draw a path, parameter

Drawbitmap (Bitmap Bitmap, rect src, rect dst, paint paint)//map, parameter one is our regular Bitmap object, parameter two is the source area (here is Bitmap), the parameter three is the target area ( Should be in the canvas location and size), parameter four is the paint brush object, because it is possible to use scaling and stretching, and when the original rect is not equal to the target rect, there will be a significant loss of performance.

DrawLine (float StartX, float starty, float stopx, float stopy, paintpaint)//Draw line, the x-axis position of a starting point of the parameter, the y-axis position of the parameter two starting point, the x-axis horizontal position of the three end of the parameter, Parameter four the vertical position of the y-axis, and the last parameter is the paint brush object.

Drawpoint (float x, float y, paint paint)//Draw point, parameter one horizontal x axis, parameter two vertical y axis, third parameter is paint object.

DrawText (string text, float x, floaty, paint paint)//rendered text, canvas class In addition to the above can also depict text, parameter one is a String type of text, parameter two x axis, parameter three Y axis, Parameter four is the Paint object.

DrawOval (RECTF oval, paint paint)//Draw ellipse, parameter one is scan area, parameter two is Paint object;

drawcircle (float cx, float CY, float radius,paint paint)//Draw circle, parameter one is the x-axis of the center point, parameter two is the y-axis of the center point, and the parameter is the radius, Parameter four is the Paint object;

DrawArc (RECTF oval, float startangle, float sweepAngle, Boolean usecenter, Paint paint)//ARC,

Parameter one is the RECTF object, the boundary of a rectangular area ellipse is used to define the shape, size, arc, parameter two is the starting angle (degrees) at the beginning of the arc,

Parameter three sweep angle (degrees) begins to measure clockwise, parameter four is if this is true, including the Oval center arc, and close it if it is false it will be an arc, parameter five is the Paint object;

Also understand a paint class:

Class Overview

The Paint class holds the style and color information about what to draw geometries, text and bitmaps.

The Paint class has style and color information on how to draw geometry, text, and bitmaps.

Paint represents the brushes, brushes, pigments, etc. on canvas;

Common methods of paint class:

Setargb (int A, int r, int g, int b)//Set Paint object color, parameter one is Alpha transparent value

Setalpha (int a)//set alpha opacity, range 0~255

Setantialias (Boolean AA)//whether anti-aliasing

SetColor (int color)//Set color, here the Android internal definition has a color class containing some common color definitions

Settextscalex (float ScaleX)//Set text magnification, 1.0f to original

Settextsize (float textSize)//Set Font size

Setunderlinetext (Booleanunderlinetext)//Set Underline

2, directly see the case

Take a look:

In this case, we are using a custom view class;

Customactivity.java

 Public classCustomactivityextendsActivity {@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main);    Init (); }    Private voidinit () {linearlayout layout=(LinearLayout) Findviewbyid (r.id.root); FinalDrawview view=NewDrawview ( This); View.setminimumheight (500); View.setminimumwidth (300); //Notification View Component redrawview.invalidate ();            Layout.addview (view); }}

Important Class Custom view component to override the view component's OnDraw (Canvase) method, the next step is to draw a large number of geometries on the canvas, points, lines, arcs, circles, ellipses, text, rectangles, polygons, curves, rounded rectangles, and so on in various shapes!

Drawview.java
 Public classDrawviewextendsView { PublicDrawview (Context context) {Super(context); } @Overrideprotected voidOnDraw (canvas canvas) {Super. OnDraw (canvas); /** Method Description DrawRect Draw Rectangle Drawcircle Draw Circle DrawOval Draw Ellipse DrawPath draw freeform * DrawLine draw line Drawpoin draw point */        //Create a brushPaint p =NewPaint (); P.setcolor (color.red);//Set RedCanvas.drawtext ("Draw a circle:", ten, p);//Draw TextCanvas.drawcircle (P);//Small CircleP.setantialias (true);//sets the jagged effect of the brush. True is the removal, you see the effect will understandCanvas.drawcircle (+, +, p);//Great CircleCanvas.drawtext ("Draw lines and arcs:", 10, 60, p); P.setcolor (color.green);//Set GreenCanvas.drawline (max., Max., p);//Draw LineCanvas.drawline (Max, Max, Max, p);//Slash//draw a smiley curveP.setstyle (Paint.Style.STROKE);//Set HollowRECTF oval1=NewRECTF (150,20,180,40); Canvas.drawarc (Oval1,180, 180,false, p);//Small ArcOval1.set (190, 20, 220, 40); Canvas.drawarc (Oval1,180, 180,false, p);//Small ArcOval1.set (160, 30, 210, 60); Canvas.drawarc (Oval1,0, 180,false, p);//Small ArcCanvas.drawtext ("Draw Rectangle:", 10, 80, p); P.setcolor (Color.gray);//Set GrayP.setstyle (Paint.Style.FILL);//Set FillCanvas.drawrect (max., p);//SquareCanvas.drawrect (max, N, p);//RectangularCanvas.drawtext ("Draw sector and Ellipse:", 10, 120, p); /*set the gradient color of the square is changed*/Shader Mshader=NewLinearGradient (0, 0, 100, 100,                New int[] {color.red, Color.green, Color.Blue, Color.yellow, Color.ltgray},NULL, Shader.TileMode.REPEAT);//a material that creates a linear gradient along a line. P.setshader (Mshader); //P.setcolor (color.blue);RECTF Oval2 =NewRECTF (60, 100, 200, 240);//set a new rectangle, scan the measurementCanvas.drawarc (Oval2, 200, 130,true, p); //arc, the first parameter is RECTF: The class is the second parameter is the beginning of the angle, the third parameter is how many degrees, the fourth parameter is true when the fan, is false when the arc is drawn//draw the oval and change the oval.Oval2.set (210,100,250,130);        Canvas.drawoval (Oval2, p); Canvas.drawtext ("Draw triangle:", 10, 200, p); //Draw this triangle and you can draw any polygonPath PATH =NewPath (); Path.moveto (80, 200);//this point is the starting point of the polygonPath.lineto (120, 250); Path.lineto (80, 250); Path.close (); //make these points form a closed polygoncanvas.drawpath (path, p); //you can draw a lot of freeform polygons, like the six shapes belowP.reset ();// ResetP.setcolor (Color.ltgray); P.setstyle (Paint.Style.STROKE);//Set HollowPath path1=NewPath (); Path1.moveto (180, 200); Path1.lineto (200, 200); Path1.lineto (210, 210); Path1.lineto (200, 220); Path1.lineto (180, 220); Path1.lineto (170, 210); Path1.close ();//closedCanvas.drawpath (path1, p); /** The path class encapsulates the compound (the paths of the multi-contour geometry * are made of straight line segments *, two curves, and three square curves, and can also be drawn with oil paintings.)         DrawPath (path, paint), either filled or stroked * (paint-based style), or can be used to cut or draw text in the path. */                //Draw rounded rectanglesP.setstyle (Paint.Style.FILL);//FullP.setcolor (Color.ltgray); P.setantialias (true);//set the brush's jagged effectCanvas.drawtext ("Draw rounded rectangles:", 10, 260, p); RECTF Oval3=NewRECTF (80, 260, 200, 300);//set a new rectangleCanvas.drawroundrect (OVAL3, p);//The second parameter is the X-radius, and the third parameter is the Y-radius//Draw Bezier CurvesCanvas.drawtext ("Drawing Bezier curve:", 10, 310, p);        P.reset ();        P.setstyle (Paint.Style.STROKE);        P.setcolor (Color.green); Path path2=NewPath (); Path2.moveto (100, 320);//set the starting point for pathPath2.quadto (150, 310, 170, 400);//set the control point coordinates and the end point coordinates of a Bezier curveCanvas.drawpath (path2, p);//draw a Bezier curve//Draw pointsP.setstyle (Paint.Style.FILL); Canvas.drawtext ("Draw point:", 10, 390, p); Canvas.drawpoint (390, p);//Draw a dotCanvas.drawpoints (New float[]{60,400,65,400,70,400}, p);//Draw multiple points//a picture is a mapBitmap Bitmap =Bitmapfactory.decoderesource (Getresources (), r.drawable.ic_launcher); Canvas.drawbitmap (Bitmap,250,360, p); }}

Android uses canvas to draw various graphics and paint usages.

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.