这个例子,自定义了一个View,可以接受touch动作,然后在屏幕上即时的显示出touch的轨迹,类似于线条的涂鸦。这个例子主要是演示如何将onTouchEvent与draw配合起来使用。在这个基础上,可以做很多有用的程序。
(注意invalidate()这个方法。这个比较关键。加入这个方法的调用主要是为了强制View进行重画。)
package com.arui; 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.view.MotionEvent; import android.view.View; /** * Example for hand writing. * * @author http://blog.csdn.net/arui319 * @version 2010/09/07 * */ public class HandwritingView extends View { private Paint paint = null; private Path path = null; public HandwritingView(Context context) { super(context); path = new Path(); paint = new Paint(); paint.setColor(Color.YELLOW); paint.setStyle(Style.STROKE); paint.setAntiAlias(true); this.setBackgroundColor(Color.BLACK); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); path.moveTo(x, y); invalidate(); return true; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { int x = (int) event.getX(); int y = (int) event.getY(); path.lineTo(x, y); invalidate(); return true; } return super.onTouchEvent(event); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (path != null) { canvas.drawPath(path, paint); } } }