Java (Android): 図形を描画

device-2013-01-02-234557

MyDrawViewActivity.java

package jp.feb19.snippets;

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;

public class MyDrawViewActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyDrawView view = new MyDrawView(this);
		setContentView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}
}

MyDrawView.java

package jp.feb19.snippets;

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

public class MyDrawView extends View {

	public MyDrawView(Context context) {
		super(context);
	}
	
	@Override
	public void onDraw(Canvas canvas) {
		// グリッドを描く
		Paint paint = new Paint();
		paint.setColor(Color.CYAN);
		paint.setStrokeWidth(1);
		for (int y = 50; y < canvas.getHeight(); y = y + 50) {
			canvas.drawLine(0, y, canvas.getWidth()-1, y, paint);
		}
		for (int x = 50; x < canvas.getWidth(); x = x + 50) {
			canvas.drawLine(x, 0, x, canvas.getHeight()-1, paint);
		}
		
		// 矩形を描く
		paint.setColor(Color.GREEN);
		paint.setStrokeWidth(0);
		canvas.drawRect(25, 25, 500, 75, paint);

		// 円を描く
		paint.setColor(Color.BLUE);
		paint.setStrokeWidth(0);
		paint.setAntiAlias(true);
		canvas.drawCircle(200, 200, 100, paint);

		// 多角形を書く
		paint.setColor(Color.RED);
		Path path = new Path();
		path.moveTo(300, 300);
		path.lineTo(500, 500);
		path.lineTo(100, 500);
		canvas.drawPath(path, paint);
		
		// 文字を書く
		paint.setColor(Color.rgb(100, 100, 255));
		paint.setTextSize(100);
		paint.setAntiAlias(false);
		canvas.drawText("ほげほげ", 50, 600, paint);
		paint.setAntiAlias(true);
		canvas.drawText("ほげほげ", 50, 700, paint);
	}
}