自定义控件MyView:
package com.example.draw;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View{
ArrayList<HashMap<String, Float>> al;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context) {
super(context);
setBackgroundColor(Color.WHITE);
al=new ArrayList<HashMap<String,Float>>();
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint=new Paint();
paint.setColor(Color.GREEN);
for(int i=0;i<al.size();i++){//画点
canvas.drawCircle(al.get(i).get("x"), al.get(i).get("y"), 10, paint);
if(i>0){//连接两点
canvas.drawLine(al.get(i-1).get("x"), al.get(i-1).get("y"), al.get(i).get("x"), al.get(i).get("y"), paint);
}
}
}
}
MainActivity.java:
package com.example.draw;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class MainActivity extends Activity implements OnTouchListener {
private MyView myView;
private boolean flag=true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = new MyView(this);
setContentView(myView);
myView.setOnTouchListener(this);
}
public boolean onTouch(View v, MotionEvent event) {
float startX = event.getX();// 相对于屏幕左上角的x坐标;getX()相对于自身左上脚
float startY = event.getY();
if (flag) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
HashMap<String, Float> map = new HashMap<String, Float>();
if (myView.al.size() > 2
&& (startX > myView.al.get(0).get("x") - 20
&& startY > myView.al.get(0).get("y") - 20)
&& (startX < myView.al.get(0).get("x") + 20
&& startY < myView.al.get(0).get("y") + 20)) {
map.put("x", myView.al.get(0).get("x"));
map.put("y", myView.al.get(0).get("y"));
myView.al.add(map);
flag=false;
}
map.put("x", startX);
map.put("y", startY);
myView.al.add(map);
break;
}
} else {
for (int i = 0; i < myView.al.size(); i++) {
if((startX>myView.al.get(i).get("x")-20&&startY>myView.al.get(i).get("y")-20)
&&(startX<myView.al.get(i).get("x")+20&&startY<myView.al.get(i).get("y")+20)){
if(i==0){//最后一个点和最开始的一个点是同一个点
myView.al.get(i).put("x", startX);
myView.al.get(i).put("y", startY);
myView.al.get(myView.al.size()-1).put("x", startX);
myView.al.get(myView.al.size()-1).put("y", startY);
}else{
myView.al.get(i).put("x", startX);
myView.al.get(i).put("y", startY);
}
break;//此处如果没有break,两点可以合为一点
}
}
}
myView.invalidate();
return true;
}
}