- 性别
- 保密
- 积分
- 7
- 积分
- 92
- 精华
- 0
- 阅读权限
- 20
- 注册时间
- 2012-5-19
- 最后登录
- 2013-8-17
- 帖子
- 33
- 性别
- 保密
|
本帖最后由 sky_yx 于 2015-12-30 14:07 编辑
思路:
自定义CustomView,重写onTouch(),和onDraw()。在onTouch中识别触屏事件,并记录触屏发生的位置。为了在ACTION_DOWN发生后能够接收到后续的触屏事件,我们需要让onTouch()返回true。
Java代码
package com.ipjmc.hello;
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();
}
@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
}
}
|
|