[size=medium]思路:
自定义CustomView,重写onTouch(),和onDraw()。在onTouch中识别触屏事件,并记录触屏发生的位置。为了在ACTION_DOWN发生后能够接收到后续的触屏事件,我们需要让onTouch()返回true。
在onDraw()中,将上一次触屏的Point和这一次触屏发生的Point,连成一条直线。因为invalidate()后,canvas被清空了,我们需要用mBitmap保存每一次绘画的结果。[/size]
[img]http://dl.iteye.com/upload/attachment/0074/7089/c7cf6249-2a5c-3b0d-ae10-39519f212a6e.png[/img]
自定义CustomView,重写onTouch(),和onDraw()。在onTouch中识别触屏事件,并记录触屏发生的位置。为了在ACTION_DOWN发生后能够接收到后续的触屏事件,我们需要让onTouch()返回true。
在onDraw()中,将上一次触屏的Point和这一次触屏发生的Point,连成一条直线。因为invalidate()后,canvas被清空了,我们需要用mBitmap保存每一次绘画的结果。[/size]
[img]http://dl.iteye.com/upload/attachment/0074/7089/c7cf6249-2a5c-3b0d-ae10-39519f212a6e.png[/img]
package com.ipjmc.hello;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class CustomView extends View {
private int mLastX, mLastY; //上次触屏的位置
private int mCurrX, mCurrY; //当前触屏的位置
private Bitmap mBitmap; //保存每次绘画的结果
private Paint mPaint;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setStrokeWidth(6);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
if (mBitmap == null) {
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
//先将结果画到Bitmap上
Canvas tmpCanvas = new Canvas(mBitmap);
tmpCanvas.drawLine(mLastX, mLastY, mCurrX, mCurrY, mPaint);
//再把Bitmap画到canvas上
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mLastX = mCurrX;
mLastY = mCurrY;
mCurrX = (int) event.getX();
mCurrY = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastX = mCurrX;
mLastY = mCurrY;
break;
default:
break;
}
invalidate();
return true; //必须返回true
}
}