.xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<com.example.touchproject2.MyPaintView
android:id="@+id/paintView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
MainActivity.java文件
package com.example.touchproject2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyPaintView.java文件
package com.example.touchproject2;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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> allPoints=new ArrayList<Point>();
//接受context以及属性集合(宽度,高度等)
public MyPaintView(Context context, AttributeSet attrs) {
super(context, attrs);
super.setOnTouchListener(new OnTouchListenerImp());
}
private class OnTouchListenerImp implements OnTouchListener{
public boolean onTouch(View v, MotionEvent event) {
Point p=new Point((int)event.getX(),(int)event.getY());
if(event.getAction()==MotionEvent.ACTION_DOWN){
//用户按下,表示重新开始保存点
MyPaintView.this.allPoints=new ArrayList<Point>();
MyPaintView.this.allPoints.add(p);
}
else if(event.getAction()==MotionEvent.ACTION_UP){
//用户松开
MyPaintView.this.allPoints.add(p);
MyPaintView.this.postInvalidate();//重绘图像
}
else if(event.getAction()==MotionEvent.ACTION_MOVE){
MyPaintView.this.allPoints.add(p);
MyPaintView.this.postInvalidate();//重绘图像
}
return true;
}
}
@Override
public void draw(Canvas canvas) {
Paint p=new Paint();//依靠此类开始画线
p.setColor(Color.RED);
if(MyPaintView.this.allPoints.size()>1){
//如果有坐标点,开始绘图
Iterator<Point> iter=MyPaintView.this.allPoints.iterator();
Point first=null;
Point last=null;
while(iter.hasNext()){
if(first==null){
first=(Point)iter.next();
}else{
if(last!=null){
first=last;
}
last=(Point)iter.next();//结束
canvas.drawLine(first.x, first.y, last.x, last.y, p);
}
}
}
}
}