Android Signature Pad

repository·main·Indexed 41 days ago

https://github.com/warting/android-signaturepad

A library for drawing smooth, high-quality signatures on Android using variable-width Bézier curve interpolation. It provides support for both Jetpack Compose and legacy Android views, allowing developers to export signatures as Bitmaps or SVG documents. Key features include customizable pen styling (width, color), velocity-based stroke smoothing, undo/clear functionality, and a SignedListener for tracking signature lifecycle events.

Tokens
3K
Snippets
11
Records
15
Agent score
50%

What's inside Android Signature Pad

  1. Install Android Signature Pad via Gradle

    main

    To use the library, ensure mavenCentral() is included in your repositories block in build.gradle.

    Choose the dependency based on your UI framework:

    • Use signature-pad for Jetpack Compose views.
    • Use signature-view for legacy Android views.
    repositories {
        mavenCentral()
    }
    
    // For Jetpack Compose
    implementation 'se.warting.signature:signature-pad:<latest_version>'
    
    // For legacy Android views
    implementation 'se.warting.signature:signature-view:<latest_version>'
  2. Configure SignaturePad attributes

    main

    You can customize the appearance and behavior of the signature pad using the following attributes:

    AttributeDescriptionDefault
    penMinWidthThe minimum width of the stroke3dp
    penMaxWidthThe maximum width of the stroke7dp
    penColorThe color of the strokeColor.BLACK
    velocityFilterWeightWeight used to modify new velocity based on the previous velocity0.9
    clearOnDoubleClickWhether double-clicking clears the padfalse
  3. Use SignaturePad in Jetpack Compose

    main

    To implement the signature pad in a Compose layout, use the SignaturePadView component. You should capture the SignaturePadAdapter via the onReady callback to interact with the signature data (e.g., saving or clearing).

    var signaturePadAdapter: SignaturePadAdapter? = null
    
    SignaturePadView(onReady = {
        signaturePadAdapter = it
    })
    
    Button(onClick = {
        Log.d("", signaturePadAdapter?.getSignatureSvg() ?: "null")
    }) {
        Text("Save")
    }
  4. Export signature data as Bitmap or SVG

    main

    The SignaturePadAdapter provides several methods to retrieve the signature in different formats:

    Bitmaps

    • getSignatureBitmap(): Returns a signature bitmap with a default white background.
      • Customization: getSignatureBitmap(backgroundColor: Int, penColor: Int)
    • getTransparentSignatureBitmap(trimBlankSpace: Boolean = false): Returns a signature bitmap with a transparent background.
      • Set trimBlankSpace = true to crop the bitmap to the signature bounds, removing surrounding blank space.
      • Customization: getTransparentSignatureBitmap(penColor: Int)

    SVG

    • getSignatureSvg(): Returns the signature as a Scalable Vector Graphics (SVG) document.
  5. Configure the SignatureSDK

    main

    Use the configure method to set the visual properties of the pen used for signing. You can specify the minimum and maximum stroke widths, the pen color, and the velocity filter weight which affects how stroke width changes based on movement speed.

    Available parameters:

    • minWidth: Minimum stroke width in pixels.
    • maxWidth: Maximum stroke width in pixels.
    • penColor: The ARGB color of the pen.
    • velocityFilterWeight: A weight used to smooth velocity changes (influences stroke thickness transitions).
    sdk.configure(
        minWidth = 3,
        maxWidth = 7,
        penColor = Color.RED,
        velocityFilterWeight = 0.9f
    )
  6. Configure the SignaturePad view

    main

    The SignaturePad is an Android View used for capturing signatures. You can configure its appearance and behavior using several methods:

    Pen Styling

    • Color: Set the stroke color using setPenColor(@ColorInt color: Int) or setPenColorRes(@ColorRes colorRes: Int).
    • Stroke Width: Set the minimum and maximum stroke widths in dp using setMinWidth(minWidth: Float) and setMaxWidth(maxWidth: Float).

    Behavior

    • Clear on Double Tap: Enable or disable clearing the signature when the user double-taps the view using setClearOnDoubleClick(clearOnDoubleClick: Boolean).
    • Undo: Revert the last stroke using undo(). Check if an undo is possible with canUndo(): Boolean.
    • Clear: Remove all strokes using clear() or clearView().

    Interaction

    • Listeners: Register a SignedListener to respond to signature events using setOnSignedListener(listener: SignedListener?).
    // Example configuration
    signaturePad.apply {
        setPenColorRes(R.color.blue)
        setMinWidth(2f)
        setMaxWidth(5f)
        setClearOnDoubleClick(true)
        setOnSignedListener(object : SignedListener {
            // Implement listener methods
        })
    }
  7. Undo and Clear signatures

    main

    The SDK supports basic management of the signature state:

    • undo(): Removes the last completed stroke (a sequence from ACTION_DOWN to ACTION_UP). If no completed strokes exist, it does nothing. In-progress strokes are preserved.
    • canUndo(): Returns true if there is at least one completed stroke available to undo.
    • clear(): Wipes the entire signature, resets all internal state, and notifies listeners via onClear().
  8. Add touch events to the SignatureSDK

    main

    Feed raw touch events into the SDK using addEvent(event: Event). The SDK sanitizes these events (filtering out NaN or infinite coordinates) and processes them to build the signature curves. This is typically called from an OnTouchListener in an Android View.

    // Inside an OnTouchListener
    override fun onTouch(v: View, event: MotionEvent): Boolean {
        val sdkEvent = Event(
            timestamp = event.eventTime,
            action = event.action,
            x = event.x,
            y = event.y
        )
        signatureSDK.addEvent(sdkEvent)
        return true
    }
  9. Export the signature as a Bitmap

    main

    The SDK provides several ways to export the signature as an Android Bitmap:

    1. getSignatureBitmap(backgroundColor: Int, penColor: Int?): Returns a bitmap with a solid background color. Use this for standard image exports.
    2. getTransparentSignatureBitmap(trimBlankSpace: Boolean, penColor: Int?): Returns a bitmap with a transparent background. If trimBlankSpace is set to true, the bitmap will be cropped to the bounding box of the actual signature strokes.
    3. drawSignature(canvas: Canvas): Directly draws the current signature onto the provided Canvas.
    // Get a cropped, transparent bitmap
    val bitmap = sdk.getTransparentSignatureBitmap(
        trimBlankSpace = true,
        penColor = Color.BLACK
    )
  10. Export the signature as SVG or Bitmap

    main

    Once a signature is captured, you can export it in various formats:

    SVG Export

    • Default: getSignatureSvg(): String returns the signature as an SVG document.
    • Customized: getSignatureSvg(@ColorInt penColor: Int? = null, @ColorInt backgroundColor: Int? = null): String allows you to specify a pen color (defaults to black if null) and a background color (defaults to transparent if null).

    Bitmap Export

    • Standard: getSignatureBitmap(): Bitmap returns the current signature.
    • With Background: getSignatureBitmap(@ColorInt backgroundColor: Int, @ColorInt penColor: Int? = null): Bitmap returns a bitmap with a specific background color.
    • Transparent: getTransparentSignatureBitmap(trimBlankSpace: Boolean = false, @ColorInt penColor: Int? = null): Bitmap returns a transparent bitmap, with an option to trim empty space around the signature.
    // Export as SVG with red pen and white background
    val svgString = signaturePad.getSignatureSvg(penColor = Color.RED, backgroundColor = Color.WHITE)
    
    // Export as a transparent bitmap with trimmed whitespace
    val bitmap = signaturePad.getTransparentSignatureBitmap(trimBlankSpace = true)
  11. Handle signature lifecycle events with SignedListener

    main

    To react to user interactions, implement the SignedListener interface and register it using setOnSignedListener. The listener provides callbacks for different stages of the signing process:

    • onStartSigning(): Called when the user first touches the screen (ACTION_DOWN).
    • onSigning(): Called during continuous movement (ACTION_MOVE).
    • onSigned(): Called when the user lifts their finger (ACTION_UP).
    • onClear(): Called when the signature is cleared or emptied.
    sdk.setOnSignedListener(object : SignedListener {
        override fun onStartSigning() { /* ... */ }
        override fun onSigning() { /* ... */ }
        override fun onSigned() { /* ... */ }
        override fun onClear() { /* ... */ }
    })
  12. Export the signature as an SVG

    main

    You can retrieve the current signature as an SVG string. This is useful for high-quality vector representations of the signature.

    Methods:

    • getSignatureSvg(width: Int, height: Int): Returns a basic SVG.
    • getSignatureSvg(width: Int, height: Int, penColor: Int?, backgroundColor: Int? = null): Returns an SVG with a specific pen color and optional background color (ARGB).
    val svgString = sdk.getSignatureSvg(
        width = 500,
        height = 200,
        penColor = Color.BLACK,
        backgroundColor = Color.WHITE
    )