Android Smooth Curve Signature Sketchpad

  • 2021-09-05 00:49:18
  • OfStack

In the development of Android, in the custom view, the corresponding operation of Canvas is used to realize the drawing board similar to signature. However, one problem is that the normal Canvas operation can use the drawing board to draw the sliding of the mobile phone, but when encountering some smooth curves, it will not be smooth enough, and even have folded corners. Here, the second-order beizer curve can be used to make the curve smoother and enhance the user experience.

Define a custom SignView, inherited from View, and define four variables in it:


private Path mPath;
private Paint mPaint;
private float mX;
private float mY;

Initialize the path and brush in the constructor:


public SignView(Context context, AttributeSet attrs) {
 super(context, attrs);
 mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
 mPaint.setStyle(Paint.Style.STROKE);
 mPaint.setStrokeWidth(10);
 
 mPath = new Path();
}

To operate canvas in onDraw (), it is worth mentioning here to call drawColor method, otherwise, if it is saved as a local picture, the background will be black, and if the brush also chooses black, it will become an all-black picture:


@Override
protected void onDraw(Canvas canvas) {
 super.onDraw(canvas);
 canvas.drawColor(Color.WHITE);
 canvas.drawPath(mPath, mPaint);
}

Next, override the onTouchEvent method:


@Override
 public boolean onTouchEvent(MotionEvent event) {
  switch (event.getAction()) {
   case MotionEvent.ACTION_DOWN:
    mX = event.getX();
    mY = event.getY();
    mPath.moveTo(mX, mY);
    break;
   case MotionEvent.ACTION_MOVE:
    float x1 = event.getX();
    float y1 = event.getY();
    float cx = (x1 + mX) / 2;
    float cy = (y1 + mY) / 2;
    mPath.quadTo(mX, mY, cx, cy);
    mX = x1;
    mY = y1;
    break;
  }
  invalidate();
  return true;
 }

When the finger is pressed, get the pressed coordinates, when moving, get the current left side, and take cx and cy in the middle of two points as the control points of beizer curve, then call quadTo method to draw the second-order beizer curve, carry out connection operation, and finally call invalidate method to redraw.

This 1 makes the line more smooth drawing board control simple implementation, if you need to save as a local, or bitmap object, you need to do other 1 additional operations.


Related articles: