The Canvas can be used to draw graphics in android. It provides methods to draw oval, rectangle, picture, text, line etc.
The Paint class is used with canvas to draw objects. It holds the information of color and style.
In this example, we will draw some 2D Shapes.
We will create class that extends View and use Canvas to draw a Circle, Rectangle and Text.
Here is the complete example.
package demo1.coderzheaven.com.demo1; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; public class MainActivity extends AppCompatActivity { int initX = 200, initY = 200, radius = 100, rectWidth = 500, rectHeight = 400; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CanvasView demoview = new CanvasView(this); setContentView(demoview); } private class CanvasView extends View { public CanvasView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // custom drawing code here Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); // make the entire canvas white paint.setColor(Color.WHITE); canvas.drawPaint(paint); // draw blue circle with anti aliasing turned on paint.setAntiAlias(true); paint.setColor(Color.BLUE); canvas.drawCircle(initX, initY, radius, paint); // draw red rectangle with anti aliasing turned off paint.setAntiAlias(true); paint.setColor(Color.RED); canvas.drawRect(initX, initY + 300, rectWidth + radius, initY + rectHeight , paint); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.GREEN); paint.setTextSize(40); canvas.drawText("CoderzHeaven, Heaven of all working codes", initX, initY + 600, paint); if (Build.VERSION.SDK_INT != Build.VERSION_CODES.M) canvas.restore(); } } }