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

Example:
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);

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

//Draw a oval without rotate
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.BLUE);
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);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
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);


paint.setColor(Color.BLUE);
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. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
}

0 Response to "Draw rotated oval, canvas.drawOval + canvas.rotate"

Posting Komentar