最近项目中有个需要签名的地方,要用到手写签名,开始只是简单的实现手写签名,如图:
后来领导说,能不能实现像毛笔那样签名的效果,那好吧,领导说怎样就怎样吧,而且我也觉得这里用毛笔效果会更好些。那就只好运用贝塞尔曲线的原理了。实现如下:
/**
* This view implements the drawing canvas.
*
* It handles all of the input events and drawing functions.
*/
class PaintView extends View {
private Paint paint;
private Canvas cacheCanvas;
private Bitmap cachebBitmap;
private Path path;
private List<TimePoint> mPoints = new ArrayList<>();
private float mVelocityFilterWeight;
private float mLastTouchX;
private float mLastTouchY;
private float mLastVelocity;
private float mLastWidth;
private int mMinWidth;
private int mMaxWidth;
private RectF mDirtyRect;
public Bitmap getCachebBitmap() {
return cachebBitmap;
}
public void setSignatureBitmap(Bitmap signature) {
clear();
ensureSignatureBitmap();
RectF tempSrc = new RectF();
RectF tempDst = new RectF();
int dWidth = signature.getWidth();
int dHeight = signature.getHeight();
int vWidth = getWidth();
int vHeight = getHeight();
// Generate the required transform.
tempSrc.set(0, 0, dWidth, dHeight);
tempDst.set(0, 0, vWidth, vHeight);
Matrix drawMatrix = new Matrix();
drawMatrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.START);
Canvas canvas = new Canvas(cachebBitmap);
canvas.drawBitmap(signature, drawMatrix, null);
// setIsEmpty(false);
invalidate();
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.SignaturePad, 0, 0);
// Configurable parameters
try {
mMinWidth = a.getDimensionPixelSize(
R.styleable.SignaturePad_minWidth, convertDpToPx(3));
mMaxWidth = a.getDimensionPixelSize(
R.styleable.SignaturePad_maxWidth, convertDpToPx(12));
mVelocityFilterWeight = a.getFloat(
R.styleable.SignaturePad_velocityFilterWeight, 0.6f);
} finally {
a.recycle();
}
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.BLACK);
path = ne