Draw circle shape in Canvas in Android

Draw circle shape in canvas is very easy thing to do if you are familiar with Canvas in Android. Please checkout this tutorial if you don’t know about how to create basic Canvas, display it to ImageView and save it as Bitmap.

Here we draw one canvas of 500×500 resolution and draw circle shape in the middle of the canvas.

The below line will draw circle shape in canvas.

canvas.drawCircle(x, y, radius, paint);

Here we pass x and y as the center coordinats of the circle. radius represents the radius of the circle being drawn. And paint is the Paint for drawing circle.

Now we will write the full code to draw circle in canvas.

Paint pBackground = new Paint();
pBackground.setColor(Color.WHITE);
canvas.drawRect(0, 0, 512, 512, pBackground);
Paint pCircle = new Paint();
pCircle.setColor(Color.BLACK);
canvas.drawCircle(256, 256, 256, pCircle);
Advertisements

Draw circle shape in ImageView in Android

It is better practice to use less number of images in your android project to generate small apk file. This tutorial will help you to draw a circle of your size and set it to your ImageView or to any other View. We will use ShapeDrawable for this purpose.

Now we create ShapeDrawable of OvalShape by writing following line.

ShapeDrawable sd = new ShapeDrawable(new OvalShape());

Now we set height and width parameters of ShapeDrawable object.

sd.setIntrinsicHeight(100);
sd.setIntrinsicWidth(100);

The last thing is to set color to ShapeDrawable object.

sd.getPaint().setColor(Color.parseColor("#abcd123"));

You are ready to set this circle image to your Imageview.

ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setBackground(sd);

Here is the full code.

ShapeDrawable sd = new ShapeDrawable(new OvalShape());
sd.setIntrinsicHeight(100);
sd.setIntrinsicWidth(100);
sd.getPaint().setColor(Color.parseColor("#abcd123"));
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setBackground(sd);