scene
In Android, the brush uses the Paint class, and the Canvas uses the Canvas class to represent it.
Basic steps of drawing
First, write a custom view class inherited from view, then rewrite its onDraw method, and finally add the custom view to actvity.
Effect
Note:
Blog:
https://blog.csdn.net/badao_liumang_qizhi
Pay attention to the public address
Domineering procedural ape
Get programming related ebooks, tutorials and free downloads.
Realization
First, add an id to the layout file of the Activity to be displayed.
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/forever" tools:context=".CanvasActivity"> </FrameLayout>
Then create a new custom View class under the package. Here, MyView makes it inherit the View class and writes a construction method with one parameter and rewrites the onDraw method.
In the redraw onDraw method, create a new brush and set some properties, then use the brush to draw a rectangle at the location specified on the canvas. package com.badao.alarmmanager;
import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.view.View; public class MyView extends View { public MyView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //Define Brush Paint paint = new Paint(); //Set color paint.setColor(0xFFFF6600); //Set brush type paint.setStyle(Paint.Style.FILL); //Using a brush to draw a rectangle on the canvas canvas.drawRect(10,10,280,150,paint); } }
Then add this custom view to the activity
package com.badao.alarmmanager; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.FrameLayout; public class CanvasActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_canvas); FrameLayout frameLayout = (FrameLayout) findViewById(R.id.forever); frameLayout.addView(new MyView(this)); } }