java
public class SignatureView extends View {
private Path signaturePath;
private Paint signaturePaint;
private int signatureColor;
private float signatureStrokeWidth;
public SignatureView(Context context) {
super(context);
init();
}
public SignatureView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public SignatureView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// 初始化路径和画笔
signaturePath = new Path();
signatureColor = Color.BLACK;
signatureStrokeWidth = 5f;
signaturePaint = new Paint();
signaturePaint.setColor(signatureColor);
signaturePaint.setStyle(Paint.Style.STROKE);
signaturePaint.setStrokeWidth(signatureStrokeWidth);
signaturePaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制签名路径
canvas.drawPath(signaturePath, signaturePaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPos = event.getX();
float yPos = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
signaturePath.moveTo(xPos, yPos);
return true;
case MotionEvent.ACTION_MOVE:
signaturePath.lineTo(xPos, yPos);
break;
case MotionEvent.ACTION_UP:
// 滑动结束时的操作(如果有)
break;
}
// 重新绘制视图
invalidate();
return true;
}
// 清除签名
public void clearSignature() {
signaturePath.reset();
invalidate();
}
//获取签名位图
public Bitmap getSignatureBitmap() {
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
draw(canvas);
return bitmap;
}
// 更改笔记颜色
public void setSignatureColor(int color) {
// 设置您想要的颜色
signatureColor = color;
signaturePaint.setColor(signatureColor);
invalidate();
}
// 更改笔记大小
public void setSignatureStrokeWidth(float width) {
// 设置您想要的笔记宽度
signatureStrokeWidth = width;
signaturePaint.setStrokeWidth(signatureStrokeWidth);
invalidate();
}
}
调用方法
XML
<com.zx.mocab.views.SignatureView
android:id="@+id/signatureView"
android:layout_width="match_parent"
android:background="@drawable/rounded_rectangle_corner_10_color_white"
android:layout_height="match_parent" />
效果图