Draw Oval In Canvas View In Android

This example will explain how to draw in oval in canvas view.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it DrawOvalOnCanvas.

2.) Write following into main.xml:

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".DrawOvalOnCanvasActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>

 

 

3.) Create and write following into MyView.java:

 

package com.example.drawovaloncanvas;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {

public MyView(Context context) {
super(context);
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);

Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.GRAY);
RectF oval1 = new RectF(0, 0, getWidth(), getHeight());
canvas.drawOval(oval1, paint);

paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
RectF oval2 = new RectF(50, 50, 150, 150);
canvas.drawOval(oval2, paint);

paint.setColor(Color.BLUE);
RectF oval3 = new RectF(250, 50, 350, 400);
canvas.drawOval(oval3, paint);
}
}

 

 

4.) Run for output.

Steps:

1.) Create a project named DrawOvalOnCanvas and set the information as stated in the image.

Build Target: Android 4.4
Application Name: DrawOvalOnCanvas
Package Name: com.example.DrawOvalOnCanvas
Activity Name: DrawOvalOnCanvasActivity

drawoval1

2.) Open DrawOvalOnCanvasActivity.java file and write following code there:

 

package com.example.drawovaloncanvas;

import android.app.Activity;
import android.os.Bundle;

public class DrawOvalOnCanvasActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
}

 

3.) Compile and build the project.

Output

drawoval2