Apr 16, 2012

Draw rotated oval, canvas.drawOval + canvas.rotate

Refer to last article Draw oval on canvas, canvas.drawOval(), we can draw oval vertically or horizontally. So, how can we draw a rotated oval? We can rotate the canvas before canvas.drawOval(), and rotate reversely after draw.

Draw rotated oval, canvas.drawOval + canvas.rotate

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) {

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

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

protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub

Paint paint = new Paint();
RectF oval1 = new RectF(0, 0, getWidth(), getHeight());
canvas.drawOval(oval1, paint);

float rotate_center_x = 200;
float rotate_center_y = 200;
float rotate_angle = 20;

//Draw a oval without rotate
RectF oval2 = new RectF(rotate_center_x-150, rotate_center_y-50, rotate_center_x+150, rotate_center_y+50);
canvas.drawOval(oval2, paint);

//Draw a oval on a rotated canvas
canvas.rotate(-rotate_angle, rotate_center_x, rotate_center_y);
RectF oval3 = new RectF(rotate_center_x-150, rotate_center_y-50, rotate_center_x+150, rotate_center_y+50);
canvas.drawOval(oval3, paint);
//resume original angle
canvas.rotate(rotate_angle, rotate_center_x, rotate_center_y);

RectF oval4 = new RectF(250, 250, 350, 600);
canvas.drawOval(oval4, 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. */
public void onCreate(Bundle savedInstanceState) {
setContentView(new MyView(this));

No comments:

Post a Comment

Infolinks In Text Ads