如图:
package com.example.myview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
/**
*
* @author HTP
*
*/
public class MyView extends SurfaceView implements Callback, OnTouchListener {
private Paint p = new Paint();
private Path path = new Path();
public MyView(Context context) {
// TODO Auto-generated constructor stub
super(context);
getHolder().addCallback(this);
p.setColor(Color.RED);
p.setTextSize(20);
p.setStyle(Style.STROKE);
// 设置监听
setOnTouchListener(this);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
getHolder().addCallback(this);
p.setColor(Color.RED);
//消除锯齿
p.setAntiAlias(true);
p.setTextSize(20);
p.setStyle(Style.STROKE);
setOnTouchListener(this);
}
/**
* 自定义画的方法canvas.drawPath
*/
public void draw() {
// TODO Auto-generated method stub
Canvas canvas = getHolder().lockCanvas();
canvas.drawColor(Color.WHITE);
canvas.drawPath(path, p);
getHolder().unlockCanvasAndPost(canvas);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
draw();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
draw();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
// draw();
}
/**
* 触摸事件
*/
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(event.getX(), event.getY());
draw();
break;
case MotionEvent.ACTION_MOVE:
path.lineTo(event.getX(), event.getY());
draw();
break;
default:
break;
}
return true;
}
/**
* 清理画布
*/
public void clear() {
path.reset();
draw();
}
}