我们都知道绘制图案就不可少的几样工具,一个是画笔(Paint),一个是画布(Canvas),画布就是在屏幕上添加一块布,然后用画笔在上面画画,当然我们需要设置画笔的颜色,字体大小,字体的样式等等
// 绘制自由曲线用的画笔 myPaint = new Paint(); myPaint.setAntiAlias(true);// 消除锯齿 myPaint.setDither(true); myPaint.setColor(Color.BLACK); myPaint.setStyle(Style.STROKE); myPaint.setStrokeJoin(Join.ROUND); myPaint.setStrokeCap(Cap.ROUND); myPaint.setStrokeWidth(12);
就像上面的代码这样。
有了画笔画布,我们就要监听触摸事件,例如屏幕被按下(DOWN),移动(MOVE),移开(UP),当然在这期间,我们需要记录每一次动作的坐标,这样才能在画布上绘制出来。
@Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: touch_start(x, y); invalidate(); break; case MotionEvent.ACTION_MOVE: touch_move(x, y); invalidate(); break; case MotionEvent.ACTION_UP: touch_up(); invalidate(); break; default: break; } return true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 如果不调用这个方法,在绘制结束后会将画布清空 canvas.drawBitmap(myBitmap, 0, 0, mBitmapPaint); // 绘制路径 canvas.drawPath(myPath, myPaint); } private void touch_start(float x, float y) { myPath.reset(); myPath.moveTo(x, y); mX = x; mY = y; } private void touch_move(float x, float y) { float dx = Math.abs(x - mX); float dy = Math.abs(y - mY); if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) { myPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2); mX=x; mY=y; } } private void touch_up(){ myPath.lineTo(mX, mY); //如果少了这一句,笔触抬起时mypath重置,那么绘制的线将会消失 myCanvas.drawPath(myPath, myPaint); myPath.reset(); }
当我们绘制出来以后,我们需要更新画布,因为我们不可能画完一个东西以后我们就换一块画布,这样我们就需要一个粉笔擦,也就是更新画布。
public void clear(){ myBitmap.eraseColor(myResources.getColor(R.color.white)); //路径重置 myPath.reset(); //刷新绘制 invalidate(); }
这样一个绘制图案的程序就成功了。
