Java (Android): 画面のタッチと描画

TouchActivity

Java: TouchActivity.java

package jp.feb19.snippets;

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

public class TouchActivity extends Activity {

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

Java: TouchView.java

package jp.feb19.snippets;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class TouchView extends View {

	ArrayList<Point> points;
	public TouchView(Context context) {
		super(context);
		this.setBackgroundColor(Color.WHITE);
		points = new ArrayList<Point>();
	}

	@SuppressLint("DrawAllocation")
	@Override
	protected void onDraw(Canvas c) {
		c.drawColor(Color.BLACK);
		Paint p = new Paint();
		p.setColor(Color.RED);

		final float radius = 200;
		for (int i = 0; i < points.size(); i++) {
			Point point = points.get(i);
			c.drawCircle(point.x, point.y, radius, p);
		}

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		points = new ArrayList<Point>();
		for (int i = 0; i < event.getPointerCount(); i++) {
			Point point = new Point((int)Math.floor(event.getX(i)), (int)Math.floor(event.getY(i)));
			Log.d("TouchEvent", String.valueOf(point));
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				points.add(point);
				break;
			case MotionEvent.ACTION_MOVE:
				points.add(point);
				break;
			case MotionEvent.ACTION_UP:
				break;
			case MotionEvent.ACTION_CANCEL:
				break;
			}
		}
		invalidate();
		return true;
	}
}