How to draw circle by using canvas in android

In android there is class Canvas which will allow us to draw different patterns like line ,circle , rectangle . We need to use the another class Paint to give color attribute to the patterns we are drawing inside canvas.In this tutorial we will learn how to draw a circle in a View by using canvas.Let us start by creating a new project.

Creating new Project

Create a new project in Android Studio from File -> New Project

  1. Fill the required fields like Application name and package name and click Next
  2.  Select Basic activity and click Next, and click  Finish Button.

Now we need to create a custom view  in which we will have canvas to draw circles. So create a class and name it as  CanvasView.java (you can give any name you like) and extend to class View and override the OnDraw method . Now your code will look like follows

public class CanvasView extends View {
    public CanvasView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }
}

Next step is to create a Paint object with a color which we want to fill the circle. You can use Paint class to do the same.

Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(false);
paint.setColor(Color.GREEN);

Now finally we can draw circle in canvas using the paint object using the following code.

canvas.drawCircle(50, 50, 25, paint);

Note: 50,50 is x,y coordinates and 25 is the radius of the circle.

Here is full code for CanvasView.java .

CanvasView.java

public class CanvasView extends View {
    public CanvasView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(false);
        paint.setColor(Color.GREEN);
        canvas.drawCircle(50, 50, 25, paint);
    }
}

Now let us see how to set this view to our MainActivity.java .Just go to MainActivity.java file and set CanvasView instance in setContentView like shown in the following code.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new CanvasView(this));
    }

}

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *