Signature Pad 1.0.0 · manual

Signature Pad manual

Version 1.0.0. A short overview is in the README.md file and the release history is in the CHANGELOG.md file, both in the root folder of the package.

Overview

Signature Pad lets the user sign inside your UI with a mouse, a finger or a stylus, and gives you the result as an image, a vector drawing or data.

  • uGUI. SignaturePad is a MaskableGraphic component: add it to a UI object under a Canvas.
  • UI Toolkit. SignaturePadElement is a visual element: declare it in UXML or create it in code.
  • One engine. Both implement ISignaturePad and share the same stroke model, so a signature drawn in one view looks the same, exports the same and loads into the other.
  • Exports. PNG bytes and Texture2D (trimmed to the ink with padding by default, transparent), SVG with one filled path per stroke, JSON stroke data with timing and pen pressure.
  • Replay and validation. Load saved JSON back, replay it stroke by stroke with its recorded timing, and check that the content looks like a deliberate signature.

The ink is rasterised on the CPU: the pixels are computed from the stroke data, not by the GPU, and the exports never read the screen. Only the Built-in Render Pipeline was run (see Tested on). The pad reads pointer events only, so it works with the input back end your project uses (legacy Input Manager or Input System package). The package is C# only: no native code, no shaders, no materials, no third-party code.

Requirements

  • Unity 6000.0.84f1 or newer. Tested with 6000.0.84f1 and 6000.3.12f1 only; see Tested on.
  • The built-in modules Image Conversion, JSON Serialize and UIElements. The package declares them, so Unity enables them with the package.
  • uGUI (com.unity.ugui) for SignaturePad, its Inspector and its menu items. Every new Unity project has it. Without it these do not exist, and SignaturePadElement, SignatureData and every export still compile.
  • The Demo sample needs uGUI. In a project without it, Unity skips the sample's scripts instead of failing to compile.
  • The Input System package is optional; see Input.

Installation

From the Asset Store

  1. Open the Package Manager: Window > Package Manager in Unity 6.0, Window > Package Management > Package Manager in Unity 6.3.
  2. Select My Assets and find Signature Pad.
  3. Click Install.

Unity installs Signature Pad as a package. It appears under Packages > Signature Pad in the Project window and its files are read-only.

Demo scenes

In the Package Manager, select Signature Pad, open the Samples tab and import Demo. Unity copies the sample into your project under Assets/Samples.

Scene What it shows
00 Menu Launcher with one button per scene and a footer link to the product page, opened only when clicked.
01 Sign Here Form A uGUI form: a SignaturePad with a baseline and a "Sign here" placeholder. Clear, Undo and Redo call the pad from their On Click () lists, with no code. Save validates, writes form-ugui.png, .svg and .json, and shows the exported PNG.
02 UI Toolkit Form The same form with UIDocument; the pad is declared in UI/SignatureForm.uxml with its pen and colours as UXML attributes.
03 Gallery Save writes the JSON stroke data to a file and adds a card. At start every file is read back and its thumbnail drawn again with Fit and ToTexture. Tap a card to load it; Delete removes its file.
04 Replay Replays Data/Sample Signature.json (generated from formulas, not a real person) with its timing, at 1x, 2x or 4x; "Replay mine" replays what you signed.

Things to know:

  • Files are saved under Application.persistentDataPath/SignaturePadDemo/; the scenes show that path shortened, starting with .../.
  • The scenes load each other by name, so add all five to the Scene List in File > Build Profiles, 00 Menu first. This is needed in Play mode in the Editor as well. A missing scene is reported on screen.
  • The scenes contain no EventSystem of their own: the demo's DemoEventSystem script creates one with InputSystemUIInputModule when the Input System package is installed and active, else with StandaloneInputModule.
  • A README.txt inside the sample describes each scene.

Quick start: uGUI

Without code

  1. Choose GameObject > UI (Canvas) > Signature Pad (luanrobs) in Unity 6.3, or GameObject > UI > Signature Pad (luanrobs) in Unity 6.0. Tools > luanrobs > Signature Pad > Create Signature Pad (uGUI) does the same in both.
  2. The item creates "Signature Pad" (600 x 200 units) with a "Placeholder" child (a baseline and a "Sign here" label in Unity's built-in font). It goes under the selected object when that is inside a Canvas, else under the first Canvas of the scene, else under a new Screen Space Overlay Canvas. When the scene has no EventSystem it adds one through Unity's own menu item, which picks the input module that matches your active input handling. Everything is registered with Undo.
  3. Add a Button. In its On Click () list, drag the pad in and choose SignaturePad > Clear. Do the same for Undo, Redo or StopReplay if you want them.
  4. Press Play and sign.

You can also add the component yourself: Add Component > luanrobs > Signature Pad on a UI object under a Canvas. The scene needs an EventSystem, as for any uGUI control.

From code

using System.IO;
using Luanrobs.Signature;
using UnityEngine;
using UnityEngine.UI;

public class SignatureForm : MonoBehaviour
{
    [SerializeField] private SignaturePad pad;
    [SerializeField] private Button saveButton;
    [SerializeField] private Text status;

    private void OnEnable()
    {
        pad.Changed += Refresh;
        saveButton.onClick.AddListener(Save);
        Refresh();
    }

    private void OnDisable()
    {
        pad.Changed -= Refresh;
        saveButton.onClick.RemoveListener(Save);
    }

    private void Refresh()
    {
        if (!isActiveAndEnabled)
        {
            return;
        }

        saveButton.interactable = !pad.IsEmpty;
    }

    private void Save()
    {
        SignatureValidationResult result = pad.Validate();
        if (!result.IsValid)
        {
            status.text = "Please sign with your name (" + result.Issues + ").";
            return;
        }

        string folder = Application.persistentDataPath;
        File.WriteAllBytes(Path.Combine(folder, "signature.png"), pad.ExportPng());
        File.WriteAllText(Path.Combine(folder, "signature.svg"), pad.ExportSvg());
        File.WriteAllText(Path.Combine(folder, "signature.json"), pad.ExportJson());
        status.text = "Saved.";
    }
}

The isActiveAndEnabled check matters: a pad can raise Changed while it is being disabled or destroyed (see Events).

Quick start: UI Toolkit

In UXML

<ui:UXML xmlns:ui="UnityEngine.UIElements">
    <ui:VisualElement style="padding: 16px;">
        <Luanrobs.Signature.SignaturePadElement name="pad" style="height: 220px;"
            pen-color="#1E2D45" background-color="#FFFFFF" min-pen-width="2" max-pen-width="6"
            hint-text="Sign here" />
        <ui:Button name="clear" text="Clear" />
        <ui:Button name="save" text="Save" />
    </ui:VisualElement>
</ui:UXML>

The element also appears in the UI Builder library. Give it a size like any other element; it sets a minimum height of 64 points itself.

using System.IO;
using Luanrobs.Signature;
using UnityEngine;
using UnityEngine.UIElements;

public class ToolkitSignatureForm : MonoBehaviour
{
    [SerializeField] private UIDocument document;

    private SignaturePadElement pad;

    private void OnEnable()
    {
        VisualElement root = document.rootVisualElement;
        pad = root.Q<SignaturePadElement>("pad");
        root.Q<Button>("clear").clicked += pad.Clear;
        root.Q<Button>("save").clicked += Save;
    }

    private void Save()
    {
        if (!pad.Validate().IsValid)
        {
            return;
        }

        File.WriteAllBytes(Path.Combine(Application.persistentDataPath, "signature.png"), pad.ExportPng());
    }
}

From code

using Luanrobs.Signature;
using UnityEngine;
using UnityEngine.UIElements;

public class ToolkitSignatureFromCode : MonoBehaviour
{
    [SerializeField] private UIDocument document;

    private void Start()
    {
        var pad = new SignaturePadElement
        {
            PenColor = new Color(0.12f, 0.18f, 0.27f),
            HintText = "Sign here",
        };
        pad.style.height = 200;
        document.rootVisualElement.Add(pad);
    }
}

Units and coordinates

All positions and sizes are in pad units: canvas units for SignaturePad, panel points for SignaturePadElement. The origin is the top-left corner of the pad, X to the right, Y down. Times are seconds since the first point of the signature.

Pen widths are in pad units too, so the ink keeps its proportions when the Canvas Scaler or the panel scale changes the size on screen. A resize keeps strokes where they are in pad units (anchored to the top-left corner) and redraws them; nothing is scaled. Use SignatureData.Fit to move a signature to a pad of another size.

The uGUI component: SignaturePad

Inspector

Group Field Default Description
Pen Pen Color opaque black Ink colour of the next strokes; alpha is the ink opacity.
Pen Min Pen Width 1.5 Thinnest line in canvas units, reached when the pointer moves fast (or at zero pressure).
Pen Max Pen Width 4.5 Thickest line, drawn when the pointer stands still (or at full pressure).
Pen Use Pressure on A pen that reports pressure sets the width instead of the speed.
Pad Background Color opaque white Painted behind the ink on screen. Alpha 0 shows what is behind the pad. Not used by exports unless you pass it in the options.
Pad Tint white The inherited Graphic.color; multiplies the whole pad. Leave it white.
Pad Read Only off Ignores pointer input and hides the placeholder. Methods called from code still work.
Pad Raycast Target, Maskable on As for any uGUI graphic. Raycast Target must stay on for the pad to receive the pointer.
Placeholder Placeholder none A GameObject switched with SetActive, shown only while the pad is empty, writable, and nothing is drawn or replayed (Play mode).
Texture Resolution Scale 1 Multiplies the resolution of the ink texture, clamped to 0.25 - 4. 1 gives one texel per screen pixel on screen-space canvases, and one texel per canvas unit times Dynamic Pixels Per Unit on World Space canvases.
Texture Max Texture Size 2048 Longest side of the ink texture, clamped to 64 - 8192 and to SystemInfo.maxTextureSize. A larger pad is drawn at a lower resolution.
Events On Stroke Started, On Stroke Ended, On Changed, On Replay Finished empty UnityEvent counterparts of the C# events.

The Inspector clamps the widths (at least 0.01, maximum never below minimum). In Play mode it also shows the stroke count, the size in units and the texture size, with Clear, Undo and Redo buttons.

Canvases and scaling

The pad works under Screen Space Overlay, Screen Space Camera and World Space canvases and with every Canvas Scaler mode. Its texture resolution is Resolution Scale x root canvas scaleFactor x (pad scale / root canvas scale), capped by Max Texture Size. Pointer positions are mapped with the event's press camera (none for Overlay, else the canvas camera or Camera.main).

Edit mode

The ink exists while the application is playing. In Edit mode the component draws a quad in its background colour and creates no texture.

Disabling

A disabled pad keeps its strokes and releases its textures; it redraws when enabled again. Destroying it releases everything.

The UI Toolkit element: SignaturePadElement

UXML attributes

Attribute Property Default
pen-color PenColor opaque black
min-pen-width MinPenWidth 1.5
max-pen-width MaxPenWidth 4.5
background-color BackgroundColor opaque white
use-pressure UsePressure true
read-only ReadOnly false
show-placeholder ShowPlaceholder true
hint-text HintText "Sign here" (null is stored as "")
placeholder-color PlaceholderColor black at 35% opacity
resolution-scale ResolutionScale 1, clamped to 0.25 - 4 (NaN is stored as 1)
max-texture-size MaxTextureSize 2048, clamped to 64 - 8192 and to the device limit

Structure and USS

The element manages its own children and accepts no others: contentContainer is null, so Add throws and the inherited VisualElement.Clear() does nothing. SignaturePadElement.Clear() clears the signature.

USS class Element
luanrobs-signature-pad The pad itself. Inline styles: minimum height 64, overflow hidden.
luanrobs-signature-pad__ink Absolute child over the content rectangle that shows the ink texture.
luanrobs-signature-pad__line Placeholder baseline, at 70% of the height, 8% inset on both sides.
luanrobs-signature-pad__hint Placeholder label under the baseline.

Inline styles set only position and colour, so the hint's font and size stay stylable from USS. The children do not take the pointer. Padding and borders on the pad are respected: the ink covers the content rectangle.

The texture resolution is ResolutionScale x scaledPixelsPerPoint x the scale of the element's transform (USS scale on the pad or an ancestor), capped by MaxTextureSize. The texture is created only in Play mode, while the element is in a panel. In Edit mode (UI Builder, previews) the pad shows its background colour and the placeholder. A detached element keeps its strokes and redraws when attached again.

Pen and ink

  • Sampling. A pointer sample is stored only when it is at least half a maximum pen width away from the last stored point.
  • Smoothing. Consecutive points are joined by cubic Bezier segments.
  • Width from speed. Width at each point = min + (max - min) / (1 + speed / (150 x max)), with the speed smoothed exponentially (weight 0.6 for the previous value). A stroke starts at the mean of min and max. Fast lines get thinner, slow lines thicker.
  • Width from pressure. For a pressure stroke: min + (max - min) x pressure.
  • Dots. A tap is a round dot whose diameter is the mean of the two widths.
  • Same ink everywhere. A width never depends on later points and is recomputed from the stored points, never stored. Live drawing, Load, Replay and every export give the same ink.
  • Lag. While drawing, the ink ends one stored sample behind the pointer, because a segment is final only once the next point is known. It catches up at pointer up.
  • Settings apply to the next strokes. PenColor, MinPenWidth and MaxPenWidth are captured at pointer down; finished strokes keep their own pen. Setting MinPenWidth above MaxPenWidth raises the maximum to the same value, and the other way round. A width that is not finite or is 0 or less throws ArgumentOutOfRangeException.
  • Background. BackgroundColor changes the screen only.

Input

  • Pointer events only. SignaturePad receives IPointerDownHandler, IDragHandler and IPointerUpHandler calls from the scene's EventSystem; SignaturePadElement receives the panel's pointer down, move, up and cancel events. Unity's UI systems turn mouse, touch and pen into these events, and the package references neither input back end.
  • Legacy Input Manager. uGUI events come from StandaloneInputModule; UI Toolkit events from the panel's own input.
  • Input System package. uGUI events come from InputSystemUIInputModule; UI Toolkit events come through the event system. No setting in the package is needed.
  • Mouse. Only the left button draws. The drag threshold is turned off on the uGUI pad so the line starts under the pointer.
  • One pointer at a time. The first pointer down owns the stroke; other pointers are ignored until it ends. Drawing with several fingers at once is not supported.
  • Clamping. Live input is clamped to the pad rectangle.
  • Interruptions. In UI Toolkit, a cancel or a lost capture of the pointer that draws finishes the stroke; the cancel of another pointer (for example a palm the system rejects while a pen draws) does not. On both views, ReadOnly = true, disabling or detaching, and the application losing the focus or being paused finish it. When a pointer goes down again while its own stroke is still open (its pointer up was lost), that stroke is finished and a new one starts. A stroke is always committed, never dropped.

Pen pressure

With UsePressure on (default); off ignores every pressure.

Pointer uGUI UI Toolkit
Mouse never never
Finger never (see the note below) never
Pen, legacy Input Manager the legacy touch with the same id has type Stylus and the event pressure is above 0 pointerType is pen and the pressure is above 0
Pen, other cases event pressure strictly between 0 and 1 and no contact radius same as above

The uGUI rule has this fallback because PointerEventData carries no pointer type. A touch that reports a contact radius gets no pressure; a touch without a radius and with a pressure between 0 and 1 cannot be told from a pen and gets pressure. Whether a given device reports a radius was not verified.

The first sample of a stroke decides: if it has a pressure, every point of that stroke stores one (a later sample without pressure repeats the previous value); otherwise the whole stroke follows the speed.

What was verified: the pressure rules were exercised with synthetic events in PlayMode tests. No physical stylus or touch screen was used; real pen pressure is not verified.

Events

Event (C#) UnityEvent (uGUI) Raised when
StrokeStarted OnStrokeStarted The user puts the pointer down on the pad and a stroke starts.
StrokeEnded OnStrokeEnded A stroke of the user is finished and has become part of the content.
Changed OnChanged After every change of the finished content: a finished stroke (after StrokeEnded), Clear (only when there were strokes), Undo, Redo, Load, and each stroke of a replay.
ReplayFinished OnReplayFinished Exactly once for every accepted Replay call, when it ends.

Rules:

  • Events are System.Action, raised on the main thread after the state they announce is in place, so a handler may call back into the pad.
  • Every StrokeStarted is followed by exactly one StrokeEnded. These two are raised for user strokes only, never for replayed strokes.
  • Changed is not raised while a stroke is being drawn.
  • A command that interrupts a stroke finishes it first: Clear during a stroke raises StrokeEnded, Changed, Changed. Undo during the first stroke raises StrokeEnded, Changed (commit), Changed (undo).
  • During a replay, Changed is raised after each stroke but the last with IsReplaying true. The last Changed and ReplayFinished come with IsReplaying already false.
  • StrokeEnded, Changed and ReplayFinished can be raised while the pad is being disabled, detached or destroyed (scene unload, quit), because a stroke or replay in progress is completed then. Start handlers with if (!isActiveAndEnabled) return; or unsubscribe in OnDisable.
  • An exception thrown by a subscriber is logged with Debug.LogException and does not stop the other subscribers.
  • Destroying a uGUI pad drops every subscriber.

Undo, redo and clear

  • Undo() removes the last stroke and keeps it for Redo(). It does nothing on an empty pad or during a replay.
  • Redo() brings it back. Drawing a new stroke, Clear, Load and Replay forget the strokes that could be redone.
  • Clear() removes all strokes and cannot be undone.
  • Load and Replay can be followed by Undo, which removes the last stroke.
  • CanUndo and CanRedo tell you whether the buttons should be enabled; refresh them in Changed and ReplayFinished.

Exports

Member Returns
ExportPng(options) / SignatureData.ToPng(options) Bytes of an 8-bit RGBA PNG file.
ExportTexture(options) / SignatureData.ToTexture(options) A new readable Texture2D (RGBA32, sRGB, no mipmaps, Clamp, Bilinear, named "Signature"). You own it and must destroy it.
ExportSvg(options) / SignatureData.ToSvg(options) An SVG document as a string.
ExportJson() / SignatureData.ToJson() JSON stroke data (see JSON stroke data).

Exports from a pad equal GetData().ToXxx(options). They are rendered again from the stroke data at the requested scale: they never read the screen, they are not limited by the on-screen texture, and they do not include BackgroundColor unless you pass it in options.background. An empty signature exports without failing (an image of the whole pad without ink).

SignatureExportOptions

null means new SignatureExportOptions(). The class is [Serializable], so it can be a field of your own component.

Field Default Description
trim true Export only the rectangle around the ink plus padding, instead of the whole pad. Ignored when there is no ink inside the pad.
padding 8 Space kept around the ink on every side when trimming, in pad units. Finite and not negative. The padded area may reach outside the pad.
scale 2 Pixels per pad unit of the PNG or texture. For SVG it multiplies the width and height attributes. Finite and greater than zero.
background transparent (0, 0, 0, 0) Colour painted behind the ink. Alpha 0 gives a transparent image whose untouched pixels are exactly (0, 0, 0, 0).
maxSize 4096 Longest side of the PNG or texture in pixels, also capped at 8192. A larger image is produced at a lower scale. At least 1. Not used for SVG.

An option out of range throws ArgumentOutOfRangeException. A trimmed export is the exact crop of the untrimmed export at the same scale (as long as the size cap does not apply).

using Luanrobs.Signature;
using UnityEngine;

public static class SignatureExports
{
    // A document-friendly image: white background, 4 pixels per unit, 12 units of margin.
    public static byte[] ForDocument(ISignaturePad pad)
    {
        var options = new SignatureExportOptions
        {
            trim = true,
            padding = 12f,
            scale = 4f,
            background = Color.white,
        };
        return pad.ExportPng(options);
    }

    // The whole pad, background included, one pixel per unit.
    public static byte[] WholePad(ISignaturePad pad)
    {
        var options = new SignatureExportOptions { trim = false, scale = 1f, background = pad.BackgroundColor };
        return pad.ExportPng(options);
    }
}

JSON stroke data

One line, no whitespace, keys in this order:

{"format":"luanrobs.signature","version":1,"width":600,"height":200,"strokes":[{"color":"#000000FF","minWidth":1.5,"maxWidth":4.5,"points":[10,20,0,14,21,0.016],"pressures":[0.5,0.55]}]}
Key Meaning
format Always luanrobs.signature.
version Format version, 1 in this release.
width, height Pad size in pad units (SignatureData.Size); 0 means unknown.
strokes The strokes in drawing order; [] is a valid empty signature.
color #RRGGBBAA, upper-case hex. The reader also accepts #RRGGBB.
minWidth, maxWidth The width range of the stroke's pen.
points Flat array, three numbers per point: x, y, time (seconds since the first point of the signature).
pressures One number per point, -1 for a point without pressure. Present only when at least one point of the stroke has a pressure; when absent, every point reads back without pressure.

Numbers are formatted with float.ToString("R", CultureInfo.InvariantCulture) and read back bit for bit: SignatureData.FromJson(data.ToJson()) equals data. Unknown keys are ignored when reading. Line widths are not stored: they are recomputed from the points.

Versioning. The reader of this release accepts version 1 only and throws FormatException ("Unsupported signature data version N.") for any other. Keep the JSON as it is when you store it.

FromJson throws ArgumentNullException for null, and FormatException with an English message for: empty or whitespace text; text that is not valid JSON; a wrong format; a wrong version; missing strokes; points empty or not a multiple of 3; pressures with another length than the point count; a colour that is not #RRGGBB or #RRGGBBAA; any value the data types reject (non-finite numbers, decreasing times, invalid widths or size); and data beyond the reader's limits: more than 10,000 strokes, more than 100,000 points in all, a maxWidth above 1,000 units, or a coordinate, width or height beyond 1,000,000 units. The limits keep the time that drawing and exporting take bounded for data that comes from outside your app; ToJson does not apply them. TryFromJson returns false instead and never throws. LoadJson leaves the pad unchanged when it throws.

SVG structure

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="W" height="H" viewBox="X Y VW VH">
<rect x="X" y="Y" width="VW" height="VH" fill="#RRGGBB" fill-opacity="A"/>
<path fill="#RRGGBB" fill-opacity="A" fill-rule="nonzero" d="..."/>
</svg>
  • viewBox is the exported area in pad units (the same rectangle as the PNG before pixel snapping); width and height are that size times scale.
  • The rect is present only when background has an alpha above 0. fill-opacity is present only for an alpha below 1, with at most three decimals.
  • Exactly one path per stroke, in drawing order. Each path is a union of closed shapes (circles and quads along the stroke) filled with nonzero, so the varying width is kept. Coordinates are absolute, in pad units.
  • Numbers use the invariant culture, at most two decimals, never exponent notation. No XML declaration, comments, ids, styles, scripts or external references. Lines end with \n.
  • An empty signature gives a valid document with no path.

SVG files of a full signature are large: the demo's four-stroke signature of 287 points gave about 240 KB, because each path is made of many small shapes.

Load, fit and replay

using Luanrobs.Signature;
using UnityEngine;

public class ShowSavedSignature : MonoBehaviour
{
    [SerializeField] private SignaturePad pad;
    [SerializeField] private TextAsset savedJson;

    private void Start()
    {
        if (!SignatureData.TryFromJson(savedJson.text, out SignatureData data))
        {
            return;
        }

        // Let the layout groups size the pad, then scale and centre the signature into it, 16 units from the edges.
        Canvas.ForceUpdateCanvases();
        SignatureData fitted = data.Fit(pad.Size, 16f);
        pad.ReplayFinished += OnReplayFinished;
        pad.Replay(fitted, 2f, 0.3f);
    }

    private void OnDisable()
    {
        pad.ReplayFinished -= OnReplayFinished;
    }

    private void OnReplayFinished()
    {
        if (!isActiveAndEnabled)
        {
            return;
        }

        Debug.Log("Replay done: " + pad.StrokeCount + " strokes.");
    }
}
  • Load(data) replaces the content and raises Changed. Positions are used as they are: ink outside the pad is not shown, not exported and not counted in Bounds. Before the pad is laid out, Size reports data.Size.
  • Fit(size, padding) returns a copy scaled uniformly and centred into a pad of another size; positions, widths and Size are scaled, times and colours kept. size must be positive, so call it once the pad has a size. The uGUI pad brings its own layout up to date when Size is read, but in Start a layout group may not have sized the pad yet: call Canvas.ForceUpdateCanvases() first, as in the example.
  • Replay(data, speed = 1, maxPause = 0.5) clears the pad and draws the signature again point by point with its recorded timing, on unscaled time (it plays while Time.timeScale is 0). speed is finite and above 0; maxPause (finite, not negative) is the longest wait, in recorded seconds, between two strokes and between two points of one stroke (the pen held still); longer waits are shortened to it, so every replay ends. Each stroke keeps its own colour and widths.
  • During a replay, pointer input, Undo and Redo are ignored. StopReplay, Clear, Load, another Replay, or disabling, detaching or destroying the pad complete it at once, so the pad then holds the whole signature.
  • A replay started before the pad has a usable size waits for its first layout. The uGUI pad brings its layout up to date first, so a replay started in Start animates.
  • An empty signature, or a pad without a texture (Edit mode, disabled, detached), completes the replay at once.

Validation

Validate(rules) (on a pad, or SignatureData.Validate) never throws and returns a SignatureValidationResult with IsValid, Issues (flags) and the measured PointCount, InkLength and BoundsSize.

Rule (SignatureValidationRules) Default Fails with
(no strokes) Empty, alone
minPointCount 8 points TooFewPoints
minInkLength 0.3 x pad width InkTooShort
minBoundsWidth 0.1 x pad width BoundsTooSmall
minBoundsHeight 0.05 x pad height BoundsTooSmall
minPathRatio 1.25 x the diagonal of the box TooStraight

The bounds are the box around the recorded points, pen width not included. The fractions are multiplied by the pad size, so the same rules work for any pad and screen; when the size is unknown (0) the fraction rules cannot fail. minPathRatio compares the ink length with the diagonal of that box: one straight line, level or slanted, is about as long as the diagonal (a ratio of about 1), handwriting is much longer; 0 turns the rule off. The defaults reject a tap, a short swipe and a straight line. The class is [Serializable] with public fields, so you can tune it in the Inspector.

Validation checks the shape of the input. It does not identify a person and is not a cryptographic signature.

Placing the signature on a PDF page

For a document, export with a white or transparent background, a scale of 3 to 4 pixels per unit and a little padding (see ForDocument in Exports). Any PDF or document library that accepts PNG bytes or a Texture2D can place the result.

With PDF Maker, another package of luanrobs (separate from Signature Pad, which does not need it), the image goes onto a page like this. The example was compiled against PDF Maker 1.0.0; it was not run as part of the tests of this package.

using Luanrobs.PdfMaker;
using Luanrobs.Signature;
using UnityEngine;

public static class SignedPdf
{
    public static byte[] Create(ISignaturePad pad)
    {
        byte[] png = pad.ExportPng(new SignatureExportOptions { scale = 4f, padding = 4f });

        var document = new PdfDocument();
        PdfPage page = document.AddPage();
        Rect area = page.ContentRect;

        // 180 points wide at the top-left corner of the area inside the margins; the height follows the image.
        page.Canvas.DrawImage(PdfImage.FromPng(png), area.xMin, area.yMin, 180f);
        return document.ToBytes();
    }
}

PdfCanvas.DrawImage(image, x, y, width) takes points, with y measured down from the top of the page; the PDF Maker manual describes its units and coordinates.

Resolution and memory

  • The on-screen texture is RGBA32, sRGB, readable, sized to the pad on screen times the resolution scale, and capped by MaxTextureSize and the device limit. On very large pads it may have a lower resolution than the screen; exports are not affected.
  • A pad of W x H texels uses about 9 bytes per texel (the displayed image, the finished ink and the coverage of the stroke in progress) plus small staging textures; nothing is added per stroke. A 2048 x 512 texture uses about 9.4 MB. When the pad gets smaller and larger again, the pixel buffers are reused; the texture is re-created and the ink redrawn at every size change, so a pad whose size animates does that every frame.
  • Uploads: when the graphics device supports texture copies, only the changed rectangle is sent each frame, through a power-of-two staging texture (at least 32 x 32; one per size, created the first time it is needed and kept until the pad releases its textures).
  • On a transparent background (alpha 0) the texels next to the ink carry the ink's colour with alpha 0, so the bilinear filtering of the UI does not draw a dark fringe around light ink. This changes the texture only, not the exports. The whole texture is sent instead after a resize, a clear or a background change, when the change covers more than half the texture, or when copies are not supported.
  • When the application gets the focus back, the whole texture is sent again (a graphics device may have lost it).
  • A disabled or detached pad releases its textures; the strokes are kept.

Error handling

Wrong arguments throw and leave the pad unchanged: ArgumentNullException (null data, JSON text or stroke lists), ArgumentOutOfRangeException (pen widths, replay speed and pause, export options, SignaturePad.ResolutionScale set to NaN), ArgumentException (invalid strokes, sizes, Fit arguments), FormatException (text that is not signature data).

Nothing else throws. Commands that cannot apply do nothing: Undo on an empty pad, Redo with nothing to redo, StopReplay without a replay, pointer input on a read-only pad or during a replay. Exports never fail on an empty signature.

The package logs nothing on success. The only log it writes is Debug.LogException for an exception thrown by an event subscriber.

Threading and lifetime

The whole API is main-thread only. Nothing starts threads, tasks or coroutines. SignatureData, SignatureStroke and SignaturePoint are immutable.

A pad destroys every texture it creates itself on disable, destroy, detach and when the Editor leaves Play mode. The texture returned by ExportTexture / ToTexture is yours to Destroy.

Domain Reload

The runtime assembly holds no mutable static state (only constants and immutable values; an EditMode test checks every static field by reflection), so it needs no reset when Enter Play Mode Options skips the Domain Reload. Events are per pad. Unsubscribe your own handlers in OnDisable or OnDestroy, as in the examples.

This was run on Unity 6000.3.12f1 (2026-10-20): three Play sessions in a row with Domain Reload disabled passed, with one package texture per session.

Limits and performance

Limit Value
Pen widths finite and above 0; the pair stays ordered
ResolutionScale 0.25 - 4
MaxTextureSize 64 - 8192, and the device limit
Export maxSize at least 1, at most 8192; a scale that would place pixels more than 2^24 pixels from the pad origin is lowered as well
Replay speed finite, above 0
JSON read by FromJson / LoadJson at most 10,000 strokes and 100,000 points, maxWidth up to 1,000 units, coordinates and pad size within 1,000,000 units

What was measured (2026-10-20, Windows 11, NVIDIA GeForce RTX 3060):

  • Rasterising one 2000-point stroke into a 2048 x 512 image: 48.0 ms in the Unity 6000.3.12f1 Editor (EditMode test).
  • The same stroke exported as a 2025 x 603 PNG in the Mono Windows player (Direct3D 12): 71 ms, 109,540 bytes.
  • PNG export of the demo's 287-point signature in that player: 42 ms (1440 x 387) to 62 ms (1688 x 450), 53 to 64 KB.
  • Uploads while drawing a long stroke on a 2048-wide texture, one move per frame for 120 frames (PlayMode test, Direct3D 11): the region mode averaged about 6.2 KB per frame (6,212 bytes, at most 16,384; two staging textures in all), against about 4.2 MB per frame for full uploads (4,159,351 bytes on average; a whole texture is 4,194,304).
  • A worst case for the limits of the JSON reader: 300 points zig-zagging across a 600 x 200 pad, exported at scale 2 (1200 x 400): 2.0 s with a 1,000-unit pen and 0.7 s with a 100,000-unit pen in the Unity 6000.3.12f1 Editor (EditMode test).
  • JSON of the 287-point signature: about 9.3 KB.

Exports run on the main thread in one call; expect a frame of that length when exporting a large image. The time grows with the amount of ink: many long strokes across the pad or very wide pens take longer than a signature. Not measured: mobile devices.

Platform support

The package is C# only, with no native code and no platform-specific code. Only the platforms in the table below were run.

Tested on

This table lists what was run for version 1.0.0. A platform that says "not run" was not run. The Android emulator row (2026-10-16) ran the package as it was before the fixes of 2026-10-20 (listed in the changelog); every other row was run on the final code on 2026-10-20.

Platform Status
Windows Editor, Unity 6000.3.12f1 Run on Windows 11 (2026-10-20, after the fixes), development project, legacy Input Manager, Built-in render pipeline: 269 of 269 EditMode tests passed, including comparisons with reference images (goldens); 45 of 45 PlayMode tests passed on Direct3D 11 (uGUI pads under Overlay, Camera and World canvases with several Canvas Scaler settings, a rotated pad and a World canvas seen at an angle, the UI Toolkit pad with padding, border and a USS scale, synthetic mouse, touch and pen events, focus loss and a cancelled second pointer, GPU upload checks in both upload modes).
Windows player (Mono), Unity 6000.3.12f1 Run on Windows 11, Direct3D 12, 1280 x 720 (2026-10-20, after the fixes): a test driver walked the five demo scenes, replayed a signature on every pad, drew a stroke through each view's pointer entry points with synthetic events, checked undo, redo, clear, read-only and the JSON round trip, wrote PNG, SVG and JSON, ran the scenes' Save, Reload and Replay, and passed with no error logged.
Clean projects, Unity 6000.3.12f1 and 6000.0.84f1 Run on Windows 11 (2026-10-20, final code): the package installed from a .tgz archive into a new project created with each version. On each: 269 of 269 EditMode and 45 of 45 PlayMode tests passed, every sample scene opened with no missing scripts, and the test driver passed in a Mono Windows player.
Windows player (IL2CPP) Run on Unity 6000.3.12f1 only (2026-10-20, final code): the test driver passed. Not run with IL2CPP on 6000.0.84f1.
Android (IL2CPP) Run on x86-64 emulators only (2026-10-16): a Unity 6000.3.12f1 build on API 36 and a Unity 6000.0.84f1 build on API 24 with OpenGL ES 3 (the graphics API of the API 36 run was not recorded); the test driver passed on both. The physical-device run is the next row.
Galaxy S23 (Android 16, arm64): test driver and adb touch input passed Run on a Samsung Galaxy S23 (Android 16, arm64) with a Unity 6000.3.12f1 IL2CPP build (2026-10-20, final code): the test driver passed on the device, and touch input sent with adb input drew, undid, redid, saved and cleared strokes in the uGUI and UI Toolkit forms; the exported JSON matched the strokes sent. The demo's replay scene filled the pad by itself, and a stroke interrupted by the Home button was kept as its own stroke, separate from the next one.
Play mode with Domain Reload disabled Unity 6000.3.12f1 (2026-10-20): three Play sessions in a row passed, with one package texture per session.
Project without uGUI Unity 6000.3.12f1 (2026-10-20), without uGUI and the Input System: the package compiles, SignaturePad is absent as intended, and 252 of 252 EditMode tests passed.
Project with the Input System package only Unity 6000.3.12f1 (2026-10-20), Active Input Handling set to Input System: 269 of 269 EditMode tests passed, the sample scenes opened and the test driver passed in a Mono Windows player.
Other platforms (macOS, Linux, iOS, WebGL and the rest) not run

Also not run: a mouse, finger or pen used by a person (all input was synthetic or sent with adb input), real pen pressure, several fingers, other physical devices, URP and HDRP. Floating-point rounding can differ between CPU architectures; pixel comparisons were run on the machine above only.

Limitations

These are known and stated up front.

  • No PDF page signing. The package does not place signatures onto existing PDF pages; export a PNG and use a PDF library.
  • Not a legal or cryptographic signature. No certificates, hashing or identity checks. Validate checks the shape of the input only.
  • No handwriting recognition.
  • Not a painting tool: no brushes, fill, layers or eraser.
  • One pointer at a time. Several fingers at once are not supported.
  • The ink follows one sample behind the pointer while drawing and catches up at pointer up.
  • Pen pressure was exercised with synthetic events only. On uGUI without a legacy stylus touch, a touch without a contact radius and with a pressure between 0 and 1 is treated as a pen.
  • Clear cannot be undone.
  • Ink exists in Play mode only. In Edit mode the pads show their background (and, in UI Toolkit, the placeholder).
  • The on-screen texture is capped by MaxTextureSize; exports are not.
  • Loaded ink outside the pad is not shown, exported or counted in Bounds. Use Fit.
  • SVG files are large for long signatures, because each stroke is a union of many small shapes.
  • Work grows with the ink. Drawing, loading and exporting run on the main thread; data far beyond a signature (thousands of long strokes, very wide pens) takes longer. FromJson refuses data beyond fixed limits (see Limits and performance).
  • An animated pad size re-creates the texture and redraws the ink every frame while it changes.

API reference

Namespace: Luanrobs.Signature. Assembly: Luanrobs.Signature.

If your scripts live in an assembly definition, add a reference to Luanrobs.Signature.

ISignaturePad

Implemented by SignaturePad and SignaturePadElement.

Member Description
Color PenColor { get; set; } Ink colour of the next strokes. Default opaque black.
float MinPenWidth { get; set; } Thinnest line in pad units. Default 1.5. Throws ArgumentOutOfRangeException when not finite or 0 or less.
float MaxPenWidth { get; set; } Thickest line in pad units. Default 4.5. Same rule.
Color BackgroundColor { get; set; } Colour behind the ink on screen. Default opaque white.
bool UsePressure { get; set; } Let pen pressure set the width. Default true.
bool ReadOnly { get; set; } Ignore pointer input and hide the placeholder. Default false.
Vector2 Size { get; } Pad size in pad units; zero until laid out.
bool IsEmpty { get; }, int StrokeCount { get; } Finished strokes.
Rect Bounds { get; } Rectangle around the finished ink, line width included, clipped to the pad. Rect.zero when empty.
bool IsDrawing { get; } True between StrokeStarted and StrokeEnded.
bool IsReplaying { get; } True from Replay until it completes.
bool CanUndo { get; }, bool CanRedo { get; } Whether Undo / Redo would do something.
void Clear(), void Undo(), void Redo() See Undo, redo and clear.
SignatureData GetData() Immutable snapshot of the finished strokes with the current size. Never null.
void Load(SignatureData data) Replace the content.
void LoadJson(string json) Read JSON and load it.
void Replay(SignatureData data, float speed = 1f, float maxPause = 0.5f) Clear and draw again with the recorded timing.
void StopReplay() Complete a running replay at once.
SignatureValidationResult Validate(SignatureValidationRules rules = null) Same as GetData().Validate(rules).
Texture2D ExportTexture(SignatureExportOptions options = null) Same as GetData().ToTexture(options).
byte[] ExportPng(SignatureExportOptions options = null) Same as GetData().ToPng(options).
string ExportSvg(SignatureExportOptions options = null) Same as GetData().ToSvg(options).
string ExportJson() Same as GetData().ToJson().
event Action StrokeStarted, StrokeEnded, Changed, ReplayFinished See Events.

SignaturePad

public sealed class SignaturePad : MaskableGraphic, ISignaturePad, IPointerDownHandler, IPointerUpHandler, IDragHandler, IInitializePotentialDragHandler, present only when uGUI is in the project. Every ISignaturePad member, plus:

Member Description
GameObject Placeholder { get; set; } Shown only while the pad is empty, writable and idle (Play mode). May be null.
float ResolutionScale { get; set; } Default 1, clamped to 0.25 - 4. NaN throws ArgumentOutOfRangeException.
int MaxTextureSize { get; set; } Default 2048, clamped to 64 - 8192; the device limit applies when the texture is sized.
UnityEvent OnStrokeStarted, OnStrokeEnded, OnChanged, OnReplayFinished { get; } Inspector counterparts of the C# events.
Texture mainTexture { get; } The ink texture in Play mode while enabled; otherwise the default white texture.
OnPointerDown, OnDrag, OnPointerUp, OnInitializePotentialDrag Called by the EventSystem.

SignaturePadElement

[UxmlElement] public sealed partial class SignaturePadElement : VisualElement, ISignaturePad. Every ISignaturePad member (each setting is also a UXML attribute), plus:

Member Description
SignaturePadElement() Creates an empty pad with the default settings.
static readonly string UssClassName, InkUssClassName, LineUssClassName, HintUssClassName The USS classes listed in Structure and USS.
bool ShowPlaceholder { get; set; } Default true.
string HintText { get; set; } Default "Sign here".
Color PlaceholderColor { get; set; } Default black at 35% opacity.
float ResolutionScale { get; set; } Default 1, clamped to 0.25 - 4; NaN is stored as 1.
int MaxTextureSize { get; set; } Default 2048, clamped to 64 - 8192.
new void Clear() Clears the signature (hides VisualElement.Clear()).
VisualElement contentContainer { get; } Always null.

SignatureData

public sealed class SignatureData : IEquatable<SignatureData>. Immutable; value equality (size and strokes).

Member Description
SignatureData(Vector2 size, IEnumerable<SignatureStroke> strokes) Size finite and not negative (zero = unknown).
Vector2 Size, IReadOnlyList<SignatureStroke> Strokes, int StrokeCount, bool IsEmpty Content.
int PointCount, float InkLength, float Duration Totals; the duration is the time of the last point.
Rect Bounds Ink rectangle, line width included, clipped to the pad when the size is known.
SignatureValidationResult Validate(SignatureValidationRules rules = null) See Validation.
SignatureData Fit(Vector2 size, float padding = 0f) Scaled and centred copy.
string ToJson(), static SignatureData FromJson(string json), static bool TryFromJson(string json, out SignatureData data) See JSON stroke data.
string ToSvg(...), byte[] ToPng(...), Texture2D ToTexture(...) See Exports.

SignatureStroke

public sealed class SignatureStroke : IEquatable<SignatureStroke>. Immutable.

Member Description
SignatureStroke(IEnumerable<SignaturePoint> points, Color32 color, float minWidth, float maxWidth) At least one point, finite values, times not decreasing, 0 < minWidth <= maxWidth.
IReadOnlyList<SignaturePoint> Points, int PointCount The recorded points.
Color32 Color, float MinWidth, float MaxWidth The pen.
bool IsDot One point only.
float Length Length of the polyline through the points.
float StartTime, float EndTime, float Duration Timing.
Rect Bounds Ink rectangle, line width included; never smaller than the ink.
float GetWidth(int pointIndex) Line width at a point.

SignaturePoint

public readonly struct SignaturePoint : IEquatable<SignaturePoint>.

Member Description
const float NoPressure = -1f No pressure reported.
SignaturePoint(Vector2 position, float time, float pressure = NoPressure) Negative or NaN pressure is stored as NoPressure, above 1 as 1.
Vector2 Position, float Time, float Pressure, bool HasPressure Values.

SignatureExportOptions

[Serializable] public sealed class SignatureExportOptions: trim, padding, scale, background, maxSize (see Exports) and Clone().

SignatureValidationRules, SignatureValidationResult, SignatureIssues

  • [Serializable] public sealed class SignatureValidationRules: minPointCount, minInkLength, minBoundsWidth, minBoundsHeight, minPathRatio, Clone().
  • public readonly struct SignatureValidationResult: IsValid, Issues, PointCount, InkLength, BoundsSize.
  • [Flags] public enum SignatureIssues { None, Empty, TooFewPoints, InkTooShort, BoundsTooSmall, TooStraight }.

Editor

Assembly Luanrobs.Signature.Editor, present only when uGUI is in the project: the SignaturePad Inspector and the menu items Tools > luanrobs > Signature Pad > Create Signature Pad (uGUI), GameObject > UI (Canvas) > Signature Pad (luanrobs) (Unity 6.3) or GameObject > UI > Signature Pad (luanrobs) (Unity 6.0), and Tools > luanrobs > Signature Pad > Documentation, which opens the online manual when clicked. Unity 6000.1 and 6000.2 were not checked; there the GameObject item may appear under a separate UI submenu.

Troubleshooting and FAQ

Nothing is drawn when I drag on the uGUI pad

The scene needs an EventSystem with an input module, and the pad needs Raycast Target on. Check that no other graphic with Raycast Target on covers the pad, and that the pad is not Read Only. A replay in progress also ignores input.

The pad is only a coloured rectangle in the Scene view

Expected: ink exists in Play mode only.

The ink looks blurry

The texture may be capped. Raise Max Texture Size or Resolution Scale, or make the pad smaller on screen. Exports are not affected by either.

The whole pad is tinted

The inherited Tint (Graphic.color) multiplies background and ink. Set it to white and use Background Color and Pen Color instead.

My exported PNG has no white background

Exports are transparent by default and ignore BackgroundColor. Set background in SignatureExportOptions.

The exported image is smaller than the pad

trim is on by default: the image covers the ink plus padding. Set trim = false for the whole pad.

A loaded signature is cut off or tiny

Load uses positions as they are. Call data.Fit(pad.Size, padding) first when the pad has another size.

My handler runs when the scene unloads

StrokeEnded, Changed and ReplayFinished can be raised while the pad is disabled or destroyed. Start handlers with if (!isActiveAndEnabled) return; or unsubscribe in OnDisable.

Validate reports TooStraight

The ink is about as long as the diagonal of its box, as for one straight line. Lower minPathRatio, or set it to 0 to turn the rule off.

A replayed or loaded signature is tiny in a corner

It was fitted with Fit(pad.Size, ...) before the canvas layout had sized the pad (for example in Start, with layout groups). Call Canvas.ForceUpdateCanvases() before reading Size.

A replay finishes at once

The data is empty, or the pad has no texture (Edit mode, disabled or detached). A replay started before the first layout waits for it instead.

Finger strokes on uGUI vary with pressure

Without a legacy stylus touch, a touch event without a contact radius and with a pressure between 0 and 1 is treated as a pen. Turn Use Pressure off if your device reports finger pressure that way.

LoadJson throws FormatException

The text is not signature data of this version, or it is beyond the reader's limits; the message says why. Use SignatureData.TryFromJson to check without exceptions.

I cannot add children to SignaturePadElement

It accepts no children (contentContainer is null). Put the pad and your other elements side by side in a parent.

Support

Email: luanrobs@gmail.com

When reporting a problem, please include your Unity version, the platform, the view (uGUI or UI Toolkit), the input back end, the JSON of a signature that shows the problem, and the Console or Player log output.

Product page: https://luanrobs.com/signature-pad/

Manual online: https://luanrobs.com/signature-pad/docs/

I maintain and support this package myself. If it saves you time, a review on the Asset Store helps a lot. Thank you.