Canvas触ってみる

原秀樹さんの「Canvas使ってスタンプポンポン!」を参考にCanvas弄ってみる。

って、サンプルをコピー。

CanvasSample.java

package jp.android.canvassample;

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

public class CanvasSample extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        
        //追加
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(new StampView(this));
    }
}

StampView.java

package jp.android.canvassample;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.View;

/**
 * StampView class 
 */
public class StampView extends View{
	private Bitmap m_bitmap;
	private Canvas m_canvas;
	private int    m_touchx;
	private int    m_touchy;
	private Bitmap m_stamp;
	
	public StampView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		
		//描画用ビットマップ
		m_bitmap = Bitmap.createBitmap(320,480,Bitmap.Config.RGB_565);
		//オフスクリーンキャンバス
		m_canvas = new Canvas(m_bitmap);
		m_canvas.drawColor(Color.WHITE);
		
		m_stamp = BitmapFactory.decodeResource(context.getResources(), R.drawable.stamp);
	}
	
	@Override
	protected void onDraw(Canvas canvas){
		canvas.drawBitmap(m_bitmap, 0,0, null);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event){
		switch(event.getAction()){
		case MotionEvent.ACTION_DOWN:
			m_touchx = (int)event.getX();
			m_touchy = (int)event.getY();
			m_canvas.drawBitmap(m_stamp, 
					m_touchx - m_stamp.getWidth()/2,
					m_touchy - m_stamp.getHeight()/2, 
					null);
			invalidate();
		}
		return super.onTouchEvent(event);
	}
}

おぉ〜、動いた。

MotionEvent

 ACTION_DOWNがあるならもちろんACTION_UPもあるだろうって事で、ちょっと改造。

	@Override
	public boolean onTouchEvent(MotionEvent event){
		switch(event.getAction()){
		case MotionEvent.ACTION_DOWN:
			m_touchx = (int)event.getX();
			m_touchy = (int)event.getY();
			m_canvas.drawBitmap(m_stamp, 
					m_touchx - m_stamp.getWidth()/2,
					m_touchy - m_stamp.getHeight()/2, 
					null);
			invalidate();
		case MotionEvent.ACTION_UP:
			m_touchx = (int)event.getX();
			m_touchy = (int)event.getY();
			m_canvas.drawBitmap(m_stamp, 
					m_touchx - m_stamp.getWidth()/2,
					m_touchy - m_stamp.getHeight()/2, 
					null);
			invalidate();
		}
		return super.onTouchEvent(event);
	}

でも、上手く動かないw;*1

*1:明日聞いてみよう