Home Web Front-end H5 Tutorial Canvas draws various basic graphics

Canvas draws various basic graphics

Jul 03, 2018 am 10:54 AM
android canvas graphics draw

This article mainly introduces the method of drawing various graphics using canvas in Android programming, involving related techniques of common drawing methods in Android using the Canvas class. It has certain reference value. Friends in need can refer to it

The example of this article describes the method of drawing various graphics using canvas in Android programming. Share it with everyone for your reference, the details are as follows:

1. First, let’s talk about the canvas class:

Class Overview

The Canvas class holds the "draw" calls. To draw something, you 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 many things in it;

We can understand this Canvas as a memory area provided to us by the system (but in fact it is just a set of APIs for drawing, and the real memory is the Bitmap below), and it also provides a complete set of operations on this memory area. Methods, all these operations are drawing API. That is to say, in this way, we can already draw what we need one stroke at a time or use Graphics. What we want to draw and what we want to display are all under our own control.

This method is divided into two types according to the environment: One is to use the canvas of ordinary View to draw, and the other is to use the canvas of special SurfaceView to draw. The main difference between the two is that you can define a special thread in SurfaceView to complete the drawing work. The application does not need to wait for the View to refresh, which improves performance. The former is suitable for animations with relatively small processing volume and low frame rates, such as chess games; while the latter is mainly used for games and high-quality animation drawings.

The following are commonly used methods of the Canvas class:

drawRect(RectF rect, Paint paint) //Draw the area, parameter one is RectF An area
drawPath(Path path, Paint paint) //Draw a path, parameter one is the Path path object
drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) //Texture, parameter one It is our regular Bitmap object. The second parameter is the source area (here is the bitmap), the third parameter is the target area (the position and size that should be in the canvas), and the fourth parameter is the Paint brush object, because scaling and pulling are used. It is possible that 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 a line, the x-axis position of the starting point of parameter one, the y-axis position of the starting point of parameter two, and the x-axis level of the end point of parameter three Position, 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) //Draw a point, parameter one is the horizontal x-axis, parameter two is the vertical y-axis, and the third parameter is the Paint object.
drawText(String text, float x, floaty, Paint paint) //Rendering text, the Canvas class can also draw text in addition to the above. The first parameter is String type text, the second parameter is the x axis, and the third parameter is y Axis, parameter four 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 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)//Draw an arc,
The first parameter is the RectF object, the limit of a rectangular area ellipse is used to define the shape, size, and arc. The second parameter is the starting angle (degree) of the arc. Start,
Parameter three scan angle (degrees) starts to be measured clockwise, parameter four is if this is true, include the arc at the center of the ellipse, and close it, if it is false it will be an arc, Parameter five is the Paint object;

You also need to understand a paint class:

Class Overview

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

The paint class holds the style and color information about how to draw geometries, text and bitmaps.
Paint represents the brush, brush, paint, etc. on the Canvas;

Common methods of the Paint class:

setARGB(int a, int r, int g, int b) // Set the color of the Paint object, parameter one is the alpha transparency value
setAlpha(int a) // Set the alpha opacity, the range is 0~255
setAntiAlias( boolean aa) // Whether to anti-alias
setColor(int color) // Set the color. The Color class defined internally by Android contains some common color definitions
setTextScaleX(float scaleX) // Set the text scaling factor, 1.0f is the original
setTextSize(float textSize) //Set the font size
setUnderlineText(booleanunderlineText) //Set the underline

2. See the case directly

Look at the renderings:

In this case we use the custom view class:

CustomActivity.java

public class CustomActivity extends Activity { 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    init(); 
  } 
  private void init() { 
    LinearLayout layout=(LinearLayout) findViewById(R.id.root); 
    final DrawView view=new DrawView(this); 
    view.setMinimumHeight(500); 
    view.setMinimumWidth(300); 
    //通知view组件重绘  
    view.invalidate(); 
    layout.addView(view); 
  } 
}
Copy after login

Important class custom View components must override the onDraw(Canvase) method of the View component. The next step is to draw a large number of geometric figures on the Canvas, such as points, straight lines, arcs, circles, ellipses, text, rectangles, etc. Polygons, curves, rounded rectangles, and more!

DrawView.java

public class DrawView extends View { 
  public DrawView(Context context) { 
    super(context); 
  } 
  @Override 
  protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    /* 
     * 方法 说明 drawRect 绘制矩形 drawCircle 绘制圆形 drawOval 绘制椭圆 drawPath 绘制任意多边形 
     * drawLine 绘制直线 drawPoin 绘制点 
     */ 
    // 创建画笔 
    Paint p = new Paint(); 
    p.setColor(Color.RED);// 设置红色 
    canvas.drawText("画圆:", 10, 20, p);// 画文本 
    canvas.drawCircle(60, 20, 10, p);// 小圆 
    p.setAntiAlias(true);// 设置画笔的锯齿效果。 true是去除,大家一看效果就明白了 
    canvas.drawCircle(120, 20, 20, p);// 大圆 
    canvas.drawText("画线及弧线:", 10, 60, p); 
    p.setColor(Color.GREEN);// 设置绿色 
    canvas.drawLine(60, 40, 100, 40, p);// 画线 
    canvas.drawLine(110, 40, 190, 80, p);// 斜线 
    //画笑脸弧线 
    p.setStyle(Paint.Style.STROKE);//设置空心 
    RectF oval1=new RectF(150,20,180,40); 
    canvas.drawArc(oval1, 180, 180, false, p);//小弧形 
    oval1.set(190, 20, 220, 40); 
    canvas.drawArc(oval1, 180, 180, false, p);//小弧形 
    oval1.set(160, 30, 210, 60); 
    canvas.drawArc(oval1, 0, 180, false, p);//小弧形 
    canvas.drawText("画矩形:", 10, 80, p); 
    p.setColor(Color.GRAY);// 设置灰色 
    p.setStyle(Paint.Style.FILL);//设置填满 
    canvas.drawRect(60, 60, 80, 80, p);// 正方形 
    canvas.drawRect(60, 90, 160, 100, p);// 长方形 
    canvas.drawText("画扇形和椭圆:", 10, 120, p); 
    /* 设置渐变色 这个正方形的颜色是改变的 */ 
    Shader mShader = new LinearGradient(0, 0, 100, 100, 
        new int[] { Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, 
            Color.LTGRAY }, null, Shader.TileMode.REPEAT); // 一个材质,打造出一个线性梯度沿著一条线。 
    p.setShader(mShader); 
    // p.setColor(Color.BLUE); 
    RectF oval2 = new RectF(60, 100, 200, 240);// 设置个新的长方形,扫描测量
    canvas.drawArc(oval2, 200, 130, true, p); 
    // 画弧,第一个参数是RectF:该类是第二个参数是角度的开始,第三个参数是多少度,第四个参数是真的时候画扇形,是假的时候画弧线 
    //画椭圆,把oval改一下 
    oval2.set(210,100,250,130); 
    canvas.drawOval(oval2, p); 
    canvas.drawText("画三角形:", 10, 200, p); 
    // 绘制这个三角形,你可以绘制任意多边形 
    Path path = new Path(); 
    path.moveTo(80, 200);// 此点为多边形的起点 
    path.lineTo(120, 250); 
    path.lineTo(80, 250); 
    path.close(); // 使这些点构成封闭的多边形 
    canvas.drawPath(path, p); 
    // 你可以绘制很多任意多边形,比如下面画六连形 
    p.reset();//重置 
    p.setColor(Color.LTGRAY); 
    p.setStyle(Paint.Style.STROKE);//设置空心 
    Path path1=new Path(); 
    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();//封闭 
    canvas.drawPath(path1, p); 
    /* 
     * Path类封装复合(多轮廓几何图形的路径 
     * 由直线段*、二次曲线,和三次方曲线,也可画以油画。drawPath(路径、油漆),要么已填充的或抚摸 
     * (基于油漆的风格),或者可以用于剪断或画画的文本在路径。 
     */ 
    //画圆角矩形 
    p.setStyle(Paint.Style.FILL);//充满 
    p.setColor(Color.LTGRAY); 
    p.setAntiAlias(true);// 设置画笔的锯齿效果 
    canvas.drawText("画圆角矩形:", 10, 260, p); 
    RectF oval3 = new RectF(80, 260, 200, 300);// 设置个新的长方形 
    canvas.drawRoundRect(oval3, 20, 15, p);//第二个参数是x半径,第三个参数是y半径 
    //画贝塞尔曲线 
    canvas.drawText("画贝塞尔曲线:", 10, 310, p); 
    p.reset(); 
    p.setStyle(Paint.Style.STROKE); 
    p.setColor(Color.GREEN); 
    Path path2=new Path(); 
    path2.moveTo(100, 320);//设置Path的起点 
    path2.quadTo(150, 310, 170, 400); //设置贝塞尔曲线的控制点坐标和终点坐标
    canvas.drawPath(path2, p);//画出贝塞尔曲线 
    //画点 
    p.setStyle(Paint.Style.FILL); 
    canvas.drawText("画点:", 10, 390, p); 
    canvas.drawPoint(60, 390, p);//画一个点 
    canvas.drawPoints(new float[]{60,400,65,400,70,400}, p);//画多个点 
    //画图片,就是贴图 
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); 
    canvas.drawBitmap(bitmap, 250,360, p); 
  } 
}
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Use Canvas to imitate the method of Baidu Tieba client loading balls

##HTML5 canvas draws five-pointed stars Methods

The above is the detailed content of Canvas draws various basic graphics. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

Motorola Razr 50s shows itself as possible new budget foldable in early leak Motorola Razr 50s shows itself as possible new budget foldable in early leak Sep 07, 2024 am 09:35 AM

Motorola has released countless devices this year, although only two of them are foldables. For context, while most of the world has received the pair as the Razr 50 and Razr 50 Ultra, Motorola offers them in North America as the Razr 2024 and Razr 2

See all articles