Basic Android tutorial -- 8.3.1 three graphic tools

Source: Internet
Author: User
Tags drawtext getcolor

Basic Android tutorial -- 8.3.1 three graphic tools
 

In the last two sections, we learned about Drawable and Bitmap. They all load images. In this section, we will learn about drawing-related
Some APIs are Canvas, Paint, and Path )! This section is very important and
Basics of custom View ~ Okay. Let's talk about the content in this section ~
Official API documentation: Canvas; Paint; Path;

1. Detailed description of relevant methods 1) Paint ):

It is a paint brush used to set the painting style, such as the width (stroke width), color, transparency, and fill style.
You can directly create a Paint instance using the no-argument constructor:
Paint paint = new Paint ();
You can set the Paint attributes using the following methods. In addition, there are two types of attributes,
Drawing is related to text painting:

SetARGB(Int a, int r, int g, int B): Set the color of the painting. a indicates transparency, r, g, and B indicates the color value. SetAlpha(Int a): sets the transparency of the drawing. SetColor(Int color): Set the color of the painting, which is expressed by the color value. The color value includes the transparency and RGB color. SetAntiAlias(Boolean aa): Setting whether to use the anti-aliasing function consumes a large amount of resources and slows down the drawing speed. SetDither(Boolean dither): Set whether to use image jitters to make the color of the image more smooth and full, and the image clearer. SetFilterBitmap(Boolean filter): If this parameter is set to true, the Bitmap image is filtered out during the animation,
Display speed is accelerated. This setting depends on dither and xfermode settings. SetMaskFilter(MaskFilter maskfilter): sets the MaskFilter. Different maskfilters can be used to implement filter effects, such as filtering and stereo. SetColorFilter(ColorFilter colorfilter): sets the color filter, which can be used to achieve the effect of non-color conversion when drawing the color. SetPathEffect(PathEffect effect) sets the effect of the draw path, such as the dot draw line. SetShader(Shader shader): Set the image effect and use Shader to draw various gradient effects. SetShadowLayer(Float radius, float dx, float dy, int color): sets the shadow layer under the graph to produce the shadow effect,
Radius indicates the shadow angle, dx and dy indicate the distance between the shadow on the X and Y axes, and color indicates the shadow color. SetStyle(Paint. Style style): Set the Paint brush Style to FILL, FILL_OR_STROKE, or STROKE. SetStrokeCap(Paint. Cap cap): When the Paint brush style is STROKE or FILL_OR_STROKE, set the image style of the brush,
For example, the circle Cap. ROUND or the SQUARE style Cap. SQUARE SetSrokeJoin(Paint. Join join): sets the combination mode of each graph during painting, such as smoothing effect. SetStrokeWidth(Float width): When the paint brush style is STROKE or FILL_OR_STROKE, set the width of the brush. SetXfermode(Xfermode xfermode): sets the processing method for overlapping images, such as merging, intersection or union, which is often used to make the eraser erasure effect. SetFakeBoldText(Boolean fakeBoldText): Simulate the implementation of bold text, the effect will be very poor when set to a small font SetSubpixelText(Boolean subpixelText): setting this parameter to true helps display the text on the LCD screen. SetTextAlign(Paint. Align align): sets the alignment direction of the drawn text. SetTextScaleX(Float scaleX): sets the scale ratio of the X axis of the drawn text to achieve the text stretching effect. SetTextSize(Float textSize): Set the font size of the drawn text. SetTextSkewX(Float skewX): Set italic text. skewX is a skewed radian. SetTypeface(Typeface typeface): Set the Typeface object, that is, the font style, including bold, italic, and linefeed, non-linefeed, etc. SetUnderlineText(Boolean underlineText): Set the text effect with underlines SetStrikeThruText(Boolean strikeThruText): sets the effect of strikethrough. SetStrokeJoin(Paint. Join join): sets the appearance of the combiner. Miter: The combiner is an acute angle,
Round: the junction is an arc: BEVEL: the junction is a straight line SetStrokeMiter(Float miter): sets the tilt of the paint brush. SetStrokeCap(Paint. Cap cap): Set the bend Style
Other common methods: float Ascent(): Measure the distance from top of the baseline to the highest character.
Float Descent(): The distance from the bottom of baseline to the lowest character int BreakText(Char [] text, int index, int count, float maxWidth, float [] measuredWidth ):
Check the number of texts displayed in a row ClearShadowLayer(): Clear the shadow layer.
Other self-check documents ~
2) Canvas ):

The paint brush is ready, and then it goes to the Canvas. You can't paint it out of thin air, right ~ The common method is as follows:

FirstConstructorCanvas has two constructor methods:
Canvas (): Create an empty canvas. You can use setBitmap () to set the canvas to be drawn.
Canvas (Bitmap bitmap): Create a canvas with a bitmap object and draw the content on bitmap. Therefore, bitmap cannot be null.
Next1. 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.
For example:

DrawRect(RectF rect, Paint paint): draws an area. Parameter 1 is a RectF area. DrawPath(Path path, Paint paint): draws a Path. Parameter 1 is the Path object. DrawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint ):
Texture. Parameter 1 is our regular Bitmap object, and parameter 2 is the source region (here it is bitmap ),
Parameter 3 is the target area (the position and size of the canvas should be used), and parameter 4 is the Paint brush object,
Due to the possibility of scaling and stretching, the performance will be greatly compromised when the original Rect is not equal to the target Rect. DrawLine(Float startX, float startY, float stopX, float stopY, Paintpaint ):
Draw line, the x-axis position of the starting point of the parameter, the y-axis position of the two starting points of the parameter, and the X-axis horizontal position of the three ending points of the parameter,
The four Y axis vertical position of the parameter. The last parameter is the Paint brush object. DrawPoint(Float x, float y, Paint paint ):
Painting point, parameter 1 Horizontal X axis, parameter 2 vertical Y axis, and third parameter is the Paint object. DrawText(String text, float x, floaty, Paint paint ):
Render text. In addition to the above, the Canvas class can also depict text. Parameter 1 is String-type text,
The parameter has two x axes, three y axes, and four is the Paint object. DrawOval(RectF oval, Paint paint): draws an elliptical image. The first parameter is the scan area, and the second parameter is the paint object; DrawCircle(Float cx, float cy, float radius, Paint paint): draws a circle. The first parameter is the X axis of the center, the second parameter is the Y axis of the center, and the third parameter is the radius, parameter 4 is the paint object; DrawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint ):
Draw an arc. The first parameter is a RectF object. The boundary of an elliptical rectangle is used to define the shape, size, and arc. The second parameter is the starting angle.
(Degree) at the beginning of the arc, the parameter three scanning angle (degree) starts to be measured clockwise. Parameter four is if this is true, including the electrical power of the elliptical Center
Arc, and close it. If it is false, it will be an arc. Parameter 5 is the Paint object;

2.ClipXXX ()Method family: crop (clip) A new drawing area in the current drawing area, which is canvas
The current drawing area of the object. For example, clipRect (new Rect () indicates the current drawing area of the canvas.
3.Save ()AndRestore ()Method:
Save(): Used to save the Canvas status. After saving, you can call operations such as pan, zoom, rotate, miscut, and crop on the Canvas!
Restore(): Used to restore the State saved before the Canvas. This prevents operations performed on the Canvas after the save operation from affecting subsequent painting.
Save () and restore () must be paired (restore can be less than save, but not more). If the restore calls more than save, an error is returned!
4.Translate(Float dx, float dy ):
Translate: Move the coordinate origin of the canvas to the left and right directions to x, and move the coordinate origin of the canvas up and down. The default position of the canvas is (0, 0)
5.Scale(Float sx, float sy): expands. x is a magnification in the horizontal direction, and y is a magnification in the vertical direction.
6.Rotate(Float degrees): rotation, angle refers to the rotation angle, clockwise rotation

3) Path)

Simply put, it is a line of drawing and connecting ~ After creating our Path, you can callDrawPath(Path, paint)
Draw the image ~ The common method is as follows:

AddArc(RectF oval, float startAngle, float sweepAngle: Add a polygon to the path AddCircle(Float x, float y, float radius, Path. Direction dir): Add a circle to the path. AddOval(RectF oval, Path. Direction dir): Add an elliptical shape. AddRect(RectF rect, Path. Direction dir): Add a region AddRoundRect(RectF rect, float [] radii, Path. Direction dir): Add a rounded corner area. IsEmpty(): Determines whether the path is empty. Transform(Matrix matrix): application Matrix transformation Transform(Matrix matrix, Path dst): Apply the Matrix transformation and place the result in the new Path, that is, the second parameter.

For more advanced effects, you can use the PathEffect class!
Several:

MoveTo(Float x, float y): Do not draw, only used to move the paint brush LineTo(Float x, float y): used to draw a straight line. It is drawn from (0, 0) by default and moved with moveTo!
For example
MPath. lineTo (300,300 );
Canvas. drawPath (mPath, mPaint ); QuadTo(Float x1, float y1, float x2, float y2 ):
It is used to draw a smooth curve, that is, the besell curve. It can also be used in combination with moveTo!
RCubicTo(Float x1, float y1, float x2, float y2, float x3, float y3)
It is also used to implement the besell curve. (X1, y1) is the control point, (x2, y2) is the control point, (x3, y3) is the end point.
Same as cubicTo, but the coordinates are considered relative to the current point
On this contour. There is only one more control point ~
Draw the above curve:
MPath. moveTo (100,500 );
MPath. cubicTo (100,500,300,100,600,500 );
If you do not add the following moveTo, use (0, 0) as the starting point and (100,500) and (300,100) as the control points to draw the besell curve.
ArcTo(RectF oval, float startAngle, float sweepAngle ):
Draw an arc (actually a part of a circle or an elliptical part). ovalRectF is the rectangle of the elliptic, and startAngle is the starting angle,
SweepAngle is the end angle.
2. Try it:

If there are so many attributes, you must click it to deepen our image ~
Hey, you can either draw a picture on the View or SurfaceView. Here we can draw a picture on the View,
We define a View class and then draw it in onDraw!

/*** Created by Jay on 0015. */public class MyView extends View {private Paint mPaint; public MyView (Context context) {super (context); init () ;}public MyView (Context context Context, AttributeSet attrs) {super (context, attrs); init ();} public MyView (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr); init ();} private void init () {mPaint = new Paint (); mPaint. setAntiAlias (true); // anti-sawtooth mPaint. setColor (getResources (). getColor (R. color. puple); // paint brush color mPaint. setStyle (Paint. style. FILL); // paint brush style mPaint. setTextSize (36); // draw the text size, in px mPaint. setStrokeWidth (5); // brush width} // rewrite this method. Draw @ Override protected void onDraw (Canvas canvas) {super. onDraw (canvas );}}

Set the View in the layout. The following code is written in onDrawable ~

1) set the canvas color:
Canvas. drawColor (getResources (). getColor (R. color. yellow); // you can specify the canvas background color.
2) Draw a circle:
Canvas. drawCircle (200,200,100, mPaint); // draw a solid circle

3) Draw a rectangle:
Canvas. drawRect (0, 0,200,100, mPaint); // draw a rectangle

4) Draw Bitmap:
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher), 0, 0, mPaint);

5) draw an arc area:
Canvas. drawArc (new RectF (0, 0,100,100), 0, 90, true, mPaint); // draw an arc Area

If true is changed to false:

6) Draw a rounded rectangle
Canvas. drawRoundRect (new RectF (10, 10, 210,110), 15, 15, mPaint); // draw a rounded rectangle

7) draw an ellipse
Canvas. drawOval (new RectF (200,300,), mPaint); // draw an ellipse

8) Draw a polygon:
Path path = new Path (); path. moveTo (10, 10); // move to coordinates 10, 10 path. lineTo (100, 50); path. lineTo (200,40); path. lineTo (300, 20); path. lineTo (200, 10); path. lineTo (100, 70); path. lineTo (50, 40); path. close (); canvas. drawPath (path, mPaint );

9) Draw text:
Canvas. drawText ~, 50, 50, mPaint); // draw text

You can also draw these words along a Path:

Path path = new Path (); path. moveTo (50, 50); path. lineTo (100,100); path. lineTo (200,200); path. lineTo (300,300); path. close (); canvas. drawTextOnPath ~, Path, 50, 50, mPaint); // draw text

10) Draw a custom image:

The Code comes from the Internet:

Protected void onDraw (Canvas canvas) {super. onDraw (canvas); canvas. translate (canvas. getWidth ()/2,200); // move the position to the coordinate point of the painted paper: 150,150 canvas. drawCircle (0, 0,100, mPaint); // draw a circle // use path to draw a canvas. save (); canvas. translate (-75,-75); Path path = new Path (); path. addArc (new RectF (150,150, 180,180),-); Paint citePaint = new Paint (mPaint); citePaint. setTextSize (14); citePaint. setStrokeWidth (1); canvas. DrawTextOnPath (drawing dial ~, Path, 28, 0, citePaint); canvas. restore (); Paint tmpPaint = new Paint (mPaint); // small scale Paint brush object tmpPaint. setStrokeWidth (1); float y = 100; int count = 60; // The total number of scales for (int I = 0; I
  

 

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.