代码其实比较简单,这种需求一般出现在图库软件里面,可以让用户,触摸来在图片上面写字,画圈圈之类的。反正就是记录触摸轨迹吧。
public class TouchView extends View {
private float currentX;
private float currentY;
private Paint paint;
private Path path;
public TouchView(Context context) {
super(context);
}
public TouchView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public TouchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public TouchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(getResources().getDimension(R.dimen.paint_width));
paint.setStrokeCap(Paint.Cap.ROUND);
path = new Path();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
currentX = event.getX();
currentY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(currentX, currentY);
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
path.lineTo(currentX, currentY);
break;
}
postInvalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path, paint);
}
}
代码这就行了,比较简单。效果类似下面这种:
不要在意图片和大红背景色
需要注意的地方:
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(currentX, currentY); // 这里是 moveTo
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
path.lineTo(currentX, currentY); // 这里是 lineTo
break;
}
没有了。