Apr 13, 2012

Draw oval on canvas, canvas.drawOval()

Draw oval on canvas, canvas.drawOval()

Create a new class MyView extends View. Override the onDraw(Canvas canvas) method to draw oval on Canvas.
package com.AndroidMyCanvas;

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);
}

}


Modify main Java activity to setContentView() using our custom View, MyView.
package com.AndroidMyCanvas;

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

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


Next:
- Draw rotated oval, canvas.drawOval + canvas.rotate



No comments:

Post a Comment

Infolinks In Text Ads