1. 程式人生 > >android 繪圖、自定義元件

android 繪圖、自定義元件

package org.touch.cn;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


import android.app.ListActivity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;


public class MyPaintView  extends View{
private List<Point> allpoint = new ArrayList<Point>();//儲存所以的操作座標
public MyPaintView(Context context, AttributeSet attrs) {//接收context,同時接收屬性集合。
super(context, attrs);//呼叫父類的構造
super.setOnTouchListener(new OnTouchListenerimpl());
}
private class OnTouchListenerimpl implements OnTouchListener{


@Override
public boolean onTouch(View v, MotionEvent event) {
Point p = new Point((int)event.getX(),(int)event.getY());//將座標儲存在Point類
if(event.getAction()==MotionEvent.ACTION_DOWN){ //使用者按下
MyPaintView.this.allpoint=new ArrayList<Point>();//重繪
MyPaintView.this.allpoint.add(p);//儲存座標點

}else if(event.getAction()==MotionEvent.ACTION_MOVE){//使用者移動
MyPaintView.this.allpoint.add(p);//記錄座標點
MyPaintView.this.postInvalidate();//重繪圖形
}else if(event.getAction()==MotionEvent.ACTION_UP){//使用者鬆開
MyPaintView.this.allpoint.add(p);//記錄座標點
MyPaintView.this.postInvalidate();//重繪圖形


}

return true; //表示下面的操作不在執行了。
}

}
@Override
protected void onDraw(Canvas canvas) { //進行繪圖
Paint paint = new Paint();//依靠此類開始畫線
paint.setColor(Color.RED);
if(MyPaintView.this.allpoint.size()>0)//有座標點儲存的時候開始進行繪圖
{
Iterator<Point> iterator = MyPaintView.this.allpoint.iterator();
Point first=null;
Point last=null;
while(iterator.hasNext()){
if(first==null)
{
first= (Point)iterator.next();//取出座標
}else {
if(last!=null){//前一階段已經完成
first = last;//重新開始下一階段
}
last=(Point)iterator.next();//結果點座標
canvas.drawLine(first.x, first.y, last.x, last.y, paint);
}
}
}
}

}