Sunday, March 13, 2011

Draw a Circle on screen with Canvas

First step is to create an activity which will display the CircleView on screen and then to create a class CircleView which will actually draw the circle on the screen.

Main Activity:
package com.android;

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

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

Circle View Class:

package com.android;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

public class CircleView extends View
{
// Variables
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

// Constructor
public CircleView(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}

/ canvas onDraw Method for drawing a circle
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}

Source