1.要实现自定义view,要处理一下几个问题
1)View的绘制,onDraw方法。
2)事件处理,复写onTouchEvent方法。
2.自定义SignView
1)初始化
private void init(Context context) {
this.context = context;
this.paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
paint.setColor(Color.BLACK);
path = new Path();
}
2)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = getMeasuredWidth();
height = getMeasuredHeight();
}
3)手写签名,主要是利用了Path的moveTo和drawLine方法。
@Override
protected void onDraw(Canvas canvas) {
if (path == null) {
return;
}
canvas.drawPath(path, paint);
}
4)事件处理
Down的时候调用 moveTo方法,MOVE时调用lineTo,这样屏幕上就能显示手指划过的痕迹
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
float downX = event.getX();
float downY = event.getY();
path.moveTo(downX, downY);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
float x = event.getX();
float y = event.getY();
path.lineTo(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
5)将手写签名保存为Bitmap。通过View.draw方法
int width = signView.getMeasuredWidth();
int height = signView.getMeasuredHeight();
Bitmap bitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
signView.draw(canvas);
Demo下载:
https://download.youkuaiyun.com/download/niuyongzhi/86541558