Detailed explanation of three drawing tool classes


Introduction to this section:

We learned about Drawable and Bitmap in the last two sections, both of which load images, and in this section we want to learn about drawing. Some APIs, they are Canvas (canvas), Paint (brush), Path (path)! This section is very important and it is also our The basics of customizing View~Okay, without further ado, let’s start this section~

Official API document: Canvas; Paint; Path


1. Detailed explanation of related methods


1) Paint (brush):

is the brush, used for Set drawing style, such as line width (stroke thickness), color, transparency and fill style, etc. You can create a Paint instance directly by using the parameterless constructor: Paint paint = new Paint();

We can set the relevant properties of Paint (brush) through the following methods. In addition, There are two types of this attribute, Graphic drawing related and text drawing related:

  • setARGB(int a,int r,int g,int b): Set the drawing color, a represents transparency, r, g, b represent color values.
  • setAlpha(int a): Set the transparency of the drawn graphics.
  • setColor(int color): Set the drawing color, represented by a color value, which includes transparency and RGB color.
  • setAntiAlias(boolean aa): Set whether to use the anti-aliasing function, which will consume a lot of resources and slow down the speed of drawing graphics.
  • setDither(boolean dither): Set whether to use image dithering processing, which will make the color of the drawn picture smoother and fuller, and the image clearer
  • setFilterBitmap(boolean filter): If this item is set to true, the image will filter out the optimization operation of the Bitmap image during the animation. To speed up the display, this setting depends on the settings of dither and xfermode
  • setMaskFilter(MaskFilter maskfilter): Set MaskFilter, you can use different MaskFilter to achieve filter effects, such as filtering, Three-dimensional, etc.
  • setColorFilter(ColorFilter colorfilter): Set the color filter to achieve a color-free transformation effect when drawing colors
  • setPathEffect( PathEffect effect) Set the effect of drawing paths, such as dotted lines, etc.
  • setShader(Shader shader): Set the image effect, use Shader to draw various gradient effects
  • setShadowLayer(float radius, float dx, float dy, int color): Set a shadow layer under the graphic to produce a shadow effect. radius is the angle of the shadow, dx and dy are the distances of the shadow on the x-axis and y-axis, color is the color of the shadow
  • setStyle(Paint.Style style): Set the style of the brush , is FILL, FILL_OR_STROKE, or STROKE
  • setStrokeCap(Paint.Cap cap): When the brush style is STROKE or FILL_OR_STROKE, set the graphic style of the brush, Such as circular style Cap.ROUND, or square style Cap.SQUARE
  • setSrokeJoin(Paint.Join join): Set the way to combine graphics when drawing, such as smoothing effects, etc.
  • setStrokeWidth(float width): When the brush style is STROKE or FILL_OR_STROKE, set the thickness of the brush
  • setXfermode(Xfermode xfermode): Set the graphics Overlapping processing methods, such as merging, intersection or union, are often used to create the erasing effect of the eraser
  • setFakeBoldText(boolean fakeBoldText): Simulate the implementation of bold text, set in The effect will be very poor on small fonts
  • setSubpixelText(boolean subpixelText): Setting this item to true will help the text display on the LCD screen
  • setTextAlign(Paint.Align align): Set the alignment direction of drawn text
  • setTextScaleX(float scaleX): Set the scaling ratio of the x-axis of drawn text, which can realize the scaling of text Stretching effect
  • setTextSize(float textSize): Set the font size of drawn text
  • setTextSkewX(float skewX): Set italic text, skewX is the slanted arc
  • setTypeface(Typeface typeface): Set the Typeface object, that is, the font style, including bold, italic, serif, non-serif, etc.
  • setUnderlineText(boolean underlineText): Set the effect of underlined text
  • setStrikeThruText(boolean strikeThruText): Set the effect of strikethrough
  • setStrokeJoin(Paint.Join join): Set the appearance of the joint. Miter: The joint is an acute angle. Round: The joint is an arc: BEVEL: The joint is a straight line
  • setStrokeMiter(float miter): Set the brush inclination
  • setStrokeCap ( Paint.Cap cap): Set the style of the corner Other commonly used methods:
  • float ascent( ): Measure the distance from the baseline to the highest point of the character

1.gif

  • float descent(): The distance from the baseline to the lowest point of the character
  • int breakText(char [] text, int index, int count, float maxWidth, float[] measuredWidth): Detect how much text is displayed in a line
  • clearShadowLayer(): Clear the shadow layer Please refer to other documents by yourself~

2) Canvas:

Now that you have the brush, then go to the brush (Canvas). You can’t draw out of thin air, right~ The common methods are as follows:

The first is the construction method. There are two construction methods for Canvas:

Canvas() : Create an empty canvas. You can use the setBitmap() method to set the specific canvas for drawing.

Canvas(Bitmap bitmap): Create a canvas with a bitmap object and draw the content on the bitmap, so the bitmap must not be null.

Followed by 1.drawXXX()Method family: Draw a picture in the current drawing area with a certain coordinate value, and the layers will be superimposed. That is, the layer painted later will cover the layer painted previously. for example:

  • drawRect(RectF rect, Paint paint): Draw an area, parameter one is a RectF area
  • drawPath(Path path, Paint paint ): Draw a path, parameter one is the Path object
  • drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint): Texture, the first parameter is our regular Bitmap object, the second parameter is the source area (here is the bitmap), Parameter three is the target area (should be the position and size of the canvas), parameter four is the Paint brush object, Because of the possibility of scaling and stretching, there will be a significant performance loss when the original Rect is not equal to the target Rect.
  • drawLine(float startX, float startY, float stopX, float stopY, Paintpaint): Draw a line, the x-axis position of the starting point of parameter one, the y-axis position of the starting point of parameter two, the x-axis horizontal position of the end point of parameter three, The four parameters are the vertical position of the y-axis, and the last parameter is the Paint brush object.
  • drawPoint(float x, float y, Paint paint): To draw points, the first parameter is the horizontal x-axis, the second parameter is the vertical y-axis, and the third parameter is the Paint object.
  • drawText(String text, float x, floaty, Paint paint): To render text, the Canvas class can also draw text in addition to the above. Parameter 1 is text of type String. The second parameter is the x-axis, the third parameter is the y-axis, and the fourth parameter is the Paint object.
  • drawOval(RectF oval, Paint paint): Draw an ellipse, the first parameter is the scan area, the second parameter is the paint object;
  • drawCircle(float cx, float cy, float radius,Paint paint): Draw a circle, parameter one is the x-axis of the center point, parameter two is the y-axis of the center point, parameter three is the radius, parameter four is the paint object ;
  • drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint): To draw an arc, the first parameter is the RectF object. The boundaries of a rectangular area and ellipse are used to define the shape, size, and arc. The second parameter is the starting angle. (Degrees) At the beginning of the arc, parameter three scan angle (degrees) starts to be measured clockwise. Parameter four is if this is true, including the electrical arc at the center of the ellipse. arc, and close it, if it is false this will be an arc, parameter five is the Paint object;

2.clipXXX()Method family: In the current The drawing area is clipped to create a new drawing area. This drawing area is the canvas. The current drawing area of ​​the object. For example: clipRect(new Rect()), then the rectangular area is the current drawing area of ​​canvas

3.save()andrestore()Methods:save( ): Used to save the state of Canvas. After saving, you can call Canvas's translation, scaling, rotation, cross-cutting, cropping and other operations! restore(): Used to restore the previously saved state of Canvas. Prevent operations performed on the Canvas after saving from affecting subsequent drawing. save() and restore() should be used in pairs (restore can be less than save, but not more). If restore is called more times than save, an error will be reported!

4.translate(float dx, float dy): Translate, move the coordinate origin of the canvas x to the left and right, and y up and down. The default position of the canvas is (0,0)

5.scale(float sx, float sy): Expand, x is the magnification factor in the horizontal direction, y is the magnification factor in the vertical direction

6.rotate(float degrees): Rotation, angle refers to the angle of rotation, in the order Clock rotation


3)Path

To put it simply, it means drawing points and connecting lines~After creating our Path path, we can call Canvas drawPath(path,paint) Draw the graphics~ The common methods are 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 path
  • addOval(RectF oval, Path.Direction dir): Add an oval
  • addRect(RectF rect, Path.Direction dir):Add a region
  • addRoundRect(RectF rect, float[] radii, Path.Direction dir): Add a rounded area
  • isEmpty(): Determine whether the path is empty
  • transform(Matrix matrix): Apply matrix transformation
  • transform(Matrix matrix, Path dst): Apply the matrix transformation and put the result into the new path, which is the second parameter

Update. Advanced effects can use the PathEffect class!

Several To:

  • ##moveTo(float x, float y): will not be drawn, only used Move the moving brush
  • lineTo(float x, float y): used for straight line drawing, starting from (0, 0) by default, use moveTo to move! for example mPath.lineTo(300, 300); canvas.drawPath(mPath, mPaint);
  • quadTo(float x1, float y1, float x2, float y2): Used to draw smooth curves, that is, Bezier curves, and can also be used in conjunction with moveTo!

    2.png

  • ##rCubicTo

    (float x1, float y1, float x2, float y2, float x3, float y3) It is also used to implement Bezier curves. (x1,y1) is the control point, (x2,y2) is the control point, and (x3,y3) is the end point. Same as cubicTo, but the coordinates are considered relative to the current point on this contour. Just 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 moveTo above: draw a Bezier curve with (0,0) as the starting point, (100,500) and (300,100) as the control points

  • arcTo(RectF oval, float startAngle, float sweepAngle): Draw an arc (actually intercepting a part of a circle or ellipse) ovalRectF is the rectangle of the ellipse, startAngle is the starting angle, sweepAngle is the end angle.

2. Give it a try:

There are so many attributes, we must go through them step by step to deepen our image, right~ Hehe, you have to draw pictures on View or SurfaceView. Let’s draw on View here. We define a View class and then complete the drawing work in onDraw()!

/**
 * Created by Jay on 2015/10/15 0015.
 */
public class MyView extends View{

    private Paint mPaint;


    public MyView(Context context) {
        super(context);
        init();
    }

    public MyView(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);          //抗锯齿
        mPaint.setColor(getResources().getColor(R.color.puple));//画笔颜色
        mPaint.setStyle(Paint.Style.FILL);  //画笔风格
        mPaint.setTextSize(36);             //绘制文字大小,单位px
        mPaint.setStrokeWidth(5);           //画笔粗细
    }
    
    //重写该方法,在这里绘图
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }
    
}

Then just 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));   //设置画布背景颜色

2) Draw a circle:

4.png

canvas.drawCircle(200, 200, 100, mPaint);           //画实心圆

3) Draw a rectangle:

5.png

canvas.drawRect(0, 0, 200, 100, mPaint);            //画矩形

4) Draw Bitmap:

6.png

canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher), 0, 0, mPaint);

5) Draw arc area:

7.png

canvas.drawArc(new RectF(0, 0, 100, 100),0,90,true,mPaint);  //绘制弧形区域

If true is changed to false:

8.png


6) Draw a rounded rectangle

9.png

canvas.drawRoundRect(new RectF(10,10,210,110),15,15,mPaint); //画圆角矩形

7 )Draw ellipse

10.png

canvas.drawOval(new RectF(0,0,200,300),mPaint); //画椭圆

8)Draw polygon:

11.png

Path path = new Path();
path.moveTo(10, 10); //移动到 坐标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 :

12.png

canvas.drawText("最喜欢看曹神日狗了~",50,50,mPaint);    //绘制文字

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);    //绘制文字


13.png


10) Draw custom graphics:

Code comes from the Internet:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.translate(canvas.getWidth()/2, 200); //将位置移动画纸的坐标点:150,150
    canvas.drawCircle(0, 0, 100, mPaint); //画圆圈

    //使用path绘制路径文字
    canvas.save();
    canvas.translate(-75, -75);
    Path path = new Path();
    path.addArc(new RectF(0,0,150,150), -180, 180);
    Paint citePaint = new Paint(mPaint);
    citePaint.setTextSize(14);
    citePaint.setStrokeWidth(1);
    canvas.drawTextOnPath("绘制表盘~", path, 28, 0, citePaint);
    canvas.restore();

    Paint tmpPaint = new Paint(mPaint); //小刻度画笔对象
    tmpPaint.setStrokeWidth(1);

    float  y=100;
    int count = 60; //总刻度数

    for(int i=0 ; i <count ; i++){
        if(i%5 == 0){
            canvas.drawLine(0f, y, 0, y+12f, mPaint);
            canvas.drawText(String.valueOf(i/5+1), -4f, y+25f, tmpPaint);

        }else{
            canvas.drawLine(0f, y, 0f, y +5f, tmpPaint);
        }
        canvas.rotate(360/count,0f,0f); //旋转画纸
    }

    //绘制指针
    tmpPaint.setColor(Color.GRAY);
    tmpPaint.setStrokeWidth(4);
    canvas.drawCircle(0, 0, 7, tmpPaint);
    tmpPaint.setStyle(Paint.Style.FILL);
    tmpPaint.setColor(Color.YELLOW);
    canvas.drawCircle(0, 0, 5, tmpPaint);
    canvas.drawLine(0, 10, 0, -65, mPaint);
}

14.png

Summary of this section:

In this section we conduct the three drawing APIs under the android.graphics interface class: Canvas (canvas), Paint (brush), Path (path) There are many ways to learn, don’t memorize it, just look it up when you need it. Here we have a rough image first, where are the custom controls? Let’s get into it slowly~ Okay, that’s all, thank you~15.gif