← Back to roadmap

Drawing with Low Latency: Wet to Dry

How a pen stroke gets on screen without waiting for the next frame: unbuffered input, a front-buffered layer the display reads while you write to it, and the hard part, handing the finished stroke over to the normal View system with no blink and no double draw. Read from the androidx.graphics and Jetpack Ink sources, with two labs: pen to pixel, and the handoff.

  • Android
  • Ink
  • Graphics
  • Latency
  • Internals
On this page
  1. What you’ll study
  2. The basics
  3. Try it: the pen-to-pixel lab
  4. The high level
  5. The low level
  6. Checkpoint
  7. Why it helps
  8. The map
  9. Edge cases
  10. Cross questions
  11. Revision: key points
  12. Cheat sheet
  13. Read next
  14. The fine print

What you’ll study

  1. Where the delay between pen and pixel comes from, and why drawing faster on the UI thread cannot remove most of it.
  2. Unbuffered dispatch: what it changes, what it doesn’t, and when to ask.
  3. A front-buffered layer: a buffer the display is already reading, which you add to a few pixels at a time.
  4. What the device decides: overlay planes, and why the same code is fast on one tablet and slower on another.
  5. The hard part, the handoff: when the pen lifts, the stroke has to move from that layer into the normal View system without blinking out or showing twice.
  6. How Jetpack Ink and androidx.graphics each solve the handoff, and when to use which.

How it connects

Guide 7 ended with a stroke’s mesh being drawn, and with a rule for handing it over: add it to your own view and remove it from Ink’s in the same UI-thread loop. This guide is why that rule exists. Guide 3 explained the frame that sets the floor on latency, guide 4 the batching that unbuffered dispatch turns off, and guide 6 the prediction that covers what is left. The eraser guide that follows has to work on the dry strokes this guide ends with.

Read it at your level

Level Read You should be able to
Student The basics, the pen-to-pixel lab Say what wet and dry ink are, and why a drawing lags behind the pen
Fresher + The high level, unbuffered dispatch Say what requestUnbufferedDispatch changes and what it can’t
Junior + The front layer, overlay planes Explain why a front-buffered layer is faster, and what can go wrong with it
Mid + The handoff, the handoff lab Say what a gap and a double draw are, and why separate updates cause one or the other
Senior + Edge cases, cross questions Choose between Ink, LowLatencyCanvasView and your own layer, and say what each leaves to you

The basics

Wet ink is the stroke while the pen is down, still changing. Dry ink is the stroke after the pen lifts, when it is part of the drawing. The two words are borrowed from paint, and they name two different jobs on the screen.

A screen shows a new picture once per refresh, 60 times a second on many devices. Your app does not paint the screen. It builds a picture in a buffer, hands the buffer to the system, and the system’s compositor (SurfaceFlinger) combines your buffer with every other window’s and gives the result to the display at the next refresh. Guide 3 followed that for the UI thread: a touch waits for the start of a frame, the frame is drawn, and the result reaches the screen at a later refresh. In the model below, that is two to three refreshes at 60 Hz, 33 ms on average, for every new bit of ink. A pen moving at 1000 pixels a second is about 33 pixels ahead of its own line.

Low-latency drawing takes the wet stroke out of that path. It draws only the newest few pixels, on another thread, into a buffer the display is already reading, so the new pixels appear the next time the display passes them. Then comes a second job nobody warns you about: when the pen lifts, that special layer has to give way to the normal View system, which will draw the dry stroke through the slow path, and for a few refreshes both exist.

Try it: the pen-to-pixel lab

Four ways to get a pen sample from the app to the screen, on a model of the main thread from guide 3. Each bar is the mean time from a sample reaching the app to the pixel changing; the dark tick is the worst case. The last number turns that time into how far the ink trails the pen at the speed you set.

Interactive pen-to-pixel lab: compare buffered and unbuffered input, and drawing through the View system against a front-buffered layer, as the display rate, pen report rate, main-thread work and overlay plane change. Needs JavaScript.

Overlay plane is the model’s switch for something the HWC decides and an app can’t query. Things to try. Each starts from the lab’s defaults (Display 60 Hz, Pen reports 240 Hz, Main-thread stall 0 ms, Work per frame 6 ms, Pixel at Middle, Overlay plane Yes, Pen speed 1000 px/s) and names every setting it changes.

  • The defaults. The means are 33.4 ms for buffered input through the View system, 33.4 ms for unbuffered input through the View system, 16.7 ms for buffered input into a front layer, and 10.3 ms for unbuffered input into a front layer. At 1000 px/s the ink trails the pen by about 33, 33, 17 and 10 px.
  • Unbuffered input alone changes nothing, by the model’s rule. The first two rows are identical in every setting, because the model says the pixel cannot change before the next frame, whoever has the sample. That is a rule, not a result. The one real difference it leaves out is guide 4’s resampling, which unbuffered input skips: it holds back the newest few milliseconds of samples.
  • A front layer needs unbuffered input. Set Overlay plane to No. The front layer is now composed like any other, so buffered input into it is 33.4 ms, the same as the View system, and unbuffered input into it is 18.7 ms.
  • A busy frame hides the gain at a fast display. Set Display to 120 Hz. The two front-layer rows are both 8.4 ms, because a 6 ms frame leaves the main thread busy most of every 8.3 ms refresh, so an unbuffered sample waits for it. Now set Work per frame to 2 ms: unbuffered input is 6.2 ms and buffered 8.4 ms.
  • Position on the screen. Set Pixel at to Top, then Bottom. The View system rows go from 25.0 to 41.7 ms, because the display is scanned top to bottom. The unbuffered front-layer row is 10.3 ms at both.
  • A stall costs the front layer only when it is long. Set Main-thread stall every 50 ms to 16 ms. At 60 Hz the unbuffered front-layer row stays 10.3 ms, because it was waiting for the next scan anyway. Set Display to 120 Hz and the stall to 16 ms: it goes from 8.4 to 10.5 ms, with a worst case of 21.7 ms.

This is a model, and its results follow from its rules, not from measurements. One artefact to know: a stalled frame starts late and, by guide 3’s rule (the first frame to start after a sample takes it), picks up every sample that arrived while it waited, so for the paths that wait for a frame a stall can lower the mean while the worst case barely moves. The stall bullet above uses the unbuffered front-layer row, which doesn’t have that effect. The sample times drift against the display, as a digitizer’s do. It assumes the panel is scanned once per refresh from top to bottom and that a layer with an overlay plane is read by the display directly; the fine print lists the rest.

The high level

Step What it does What it costs
Unbuffered input Asks the input system to hand over samples as soon as the main thread can take them, not at the next frame Only helps if something else is waiting; the platform’s reference warns it is not for most apps
Draw the new bit Draws only the newest segment, on a render thread, into a buffer that keeps its contents Suits a small area; the display can read it half-written (tearing)
Show it A layer above the window whose buffer the display reads, ideally in an overlay plane The device decides whether it gets a plane
Hand off When the pen lifts, move the stroke to the normal path and clear the layer A blink or a double draw if the two changes land on different refreshes

The low level

Source excerpts are from the AOSP sources of ViewRootImpl, View and InputConsumer on main, from androidx.graphics:graphics-core 1.0.4 (the version Ink 1.0.0 depends on, as a runtime dependency, so an app that calls it needs its own implementation line), and from the Kotlin sources of androidx.ink 1.0.0, trimmed with …. Where androidx-main differs, the text says so. Links are in The map.

1. Unbuffered dispatch

Guide 4 showed that the input system batches: while your UI thread is busy, new samples for one pointer pile up in a batch, and the app collects the batch at the start of the next frame. That is good for scrolling, and it is the wait this step removes.

The app side is in ViewRootImpl. When the native receiver reports a pending batch, the default is to schedule collecting it on Choreographer’s input callback, which runs at the start of the next frame. If unbuffered dispatch has been requested, it collects the batch immediately:

// ViewRootImpl.WindowInputEventReceiver
public void onBatchedInputEventPending(int source) {
    final boolean unbuffered = mUnbufferedInputDispatch
            || (source & mUnbufferedInputSource) != SOURCE_CLASS_NONE;
    if (unbuffered) {
        if (mConsumeBatchedInputScheduled) {
            unscheduleConsumeBatchedInput();
        }
        // Consume event immediately if unbuffered input dispatch has been requested.
        consumeBatchedInputEvents(-1);
        return;
    }
    scheduleConsumeBatchedInput();   // posts CALLBACK_INPUT to the Choreographer
}

The -1 is the frame time. In the native InputConsumer::consumeBatch a negative frame time takes every sample in the batch and returns before the resampling code of guide 4:

// InputConsumer::consumeBatch, frameworks/native/libs/input/InputConsumer.cpp
if (frameTime < 0) {
    result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
    mBatches.erase(mBatches.begin() + i);
    return result;
}

So unbuffered dispatch means: not waiting for the frame, and not resampled. Two details decide whether you get it:

  • You ask with a DOWN or MOVE, and it lasts for the gesture. View.requestUnbufferedDispatch(MotionEvent) does nothing unless the event is an ACTION_DOWN or ACTION_MOVE of a touch (a pen on the glass counts; hover does not). ViewRootImpl clears the request before it dispatches each pointer event and, if a view made it again during that dispatch, switches unbuffered mode on. Once on, it stays on until a touch UP or CANCEL is delivered, when ViewRootImpl turns it off. So asking on the DOWN is enough, and Ink’s documentation says to call it alongside startStroke.
  • There is a persistent form. requestUnbufferedDispatch(int source) (API 30) takes an input source class and stays on until you pass SOURCE_CLASS_NONE. Before Android 14 it does nothing while the view is not attached to a window.

The platform reference’s own warning is plain: the call is not meant for most apps, and unbuffered dispatch has side effects, including more latency in some cases, jittery scrolling, and losing the system’s resampling. An event can also still carry several samples, because whatever arrived while the thread was busy is in its history.

class PenInputView(context: Context) : View(context) {
    private val points = ArrayList<PointF>()

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
                // Only a DOWN or MOVE counts. Once granted it lasts until UP or CANCEL.
                requestUnbufferedDispatch(event)
                // An event can still carry several samples; the older ones are its history.
                for (h in 0 until event.historySize) {
                    points.add(PointF(event.getHistoricalX(h), event.getHistoricalY(h)))
                }
                points.add(PointF(event.x, event.y))
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> points.clear()
        }
        return true
    }
}

2. Why that is not enough

Drawing through the View system is a different wait. Whoever has the sample, invalidate() asks for a frame, the frame starts at the next vsync, and the picture it makes reaches the screen at a vsync after that (guide 3). In the lab the two View-system rows are identical: unbuffered input moves the wait for the sample, and the wait for the frame is still there. What unbuffered input does for a drawing app is feed whatever draws outside the frame, which is the next step. The Ink documentation says the same thing in its API: it recommends calling requestUnbufferedDispatch alongside startStroke “for optimum performance”.

3. A front-buffered layer

The Android developer guide to advanced stylus features describes the idea: the front buffer is the memory the screen reads, the closest an app gets to drawing directly to the screen, suited to a small area and not to refreshing a whole screen, because the app is writing into a buffer the display is reading, so tearing and other artifacts are possible. The library is androidx.graphics:graphics-core, from API 29.

Here is what CanvasFrontBufferedRenderer (graphics-core 1.0.4) builds under a SurfaceView you give it:

  • A multi-buffered layer, a SurfaceControl child of the SurfaceView, that holds the dry scene.
  • A front-buffered layer, a child of that one, set to the top of the stack (setLayer(…, Integer.MAX_VALUE)).
  • For the front layer, a renderer with one buffer (setMaxBuffers(1)) that keeps its contents between draws (preserveContents(true)), so each draw adds a few pixels to what is already there.
  • Usage flags that include USAGE_COMPOSER_OVERLAY, and on Android 13 and later USAGE_FRONT_BUFFER if HardwareBuffer.isSupported says the device can do it. If not, the code falls back to USAGE_CPU_WRITE_OFTEN, and its comment says that is to prevent frame-buffer compression artifacts on certain devices such as the Galaxy Tab S6 Lite.

Each time a draw finishes, the library publishes the buffer to the compositor in a transaction. The condition on the fence is the whole trick:

// library source: CanvasFrontBufferedRenderer.onBufferReady (androidx.graphics 1.0.4), trimmed; [note] comments are mine
SurfaceControlCompat.Transaction()
    .setLayer(frontBufferSurfaceControl, Integer.MAX_VALUE)
    .setBuffer(
        frontBufferSurfaceControl,
        hardwareBuffer,
        // [note] already on screen: no fence, so the compositor does not wait for the GPU
        if (singleBufferedCanvasRenderer?.isVisible == true) null else syncFenceCompat,
    ) { releaseFence -> … }
    .setVisibility(frontBufferSurfaceControl, true)
    …
    .commit()

The first time the layer appears, the buffer comes with a fence, so the compositor waits until the drawing is finished. After that the layer is already visible, so the fence is null: the buffer is shown without waiting for the new pixels to be finished. Ink’s helper says the same in a comment on its own incremental draw: “don’t wait on a fence to show the buffer”, so that “the render races the scanline”. The same code sets a frame-rate hint of 1000 on this layer with CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS; the source does not say why, and I haven’t checked what each device does with it.

The graphics-core classes come in two flavours with the same layering: CanvasFrontBufferedRenderer draws with a Canvas, and GLFrontBufferedRenderer draws with OpenGL. A third, LowLatencyCanvasView, wraps the Canvas one in a view. Both renderers are @RequiresApi(Build.VERSION_CODES.Q).

4. Overlay planes: what the device decides

Two sentences from the platform’s documentation explain why a front layer is not always fast. The Hardware Composer page says overlay planes composite several buffers in the display hardware instead of on the GPU, and that SurfaceFlinger hands the HWC a list of layers and the HWC answers, layer by layer, whether it will handle it itself (device composition) or leaves it to the GPU (client composition). The HardwareBuffer reference says USAGE_FRONT_BUFFER makes a GPU-rendered buffer “behave similar to a single-buffered window”, and that combined with USAGE_COMPOSER_OVERLAY the system will try to give the buffer an overlay plane and avoid caching it in an intermediate composition buffer.

Whether a front layer gets a plane depends on the display hardware: the HWC page says the number of overlays, whether layers can be rotated or blended, and the limits on position and overlap all vary. If it doesn’t get one, the layer is composed like any other, and the lab’s Overlay plane: No shows what that costs. The library probes whether the buffer usages can be allocated, as in this probe of the kind its source makes. That is not a test for an overlay plane: the HWC decides planes, an app has no way to ask it, and the probe only changes which usage flags and sync strategy the library picks.

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
fun deviceOffersFrontBuffer(): Boolean =
    HardwareBuffer.isSupported(
        1, 1, HardwareBuffer.RGBA_8888, 1,
        HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or
            HardwareBuffer.USAGE_GPU_COLOR_OUTPUT or
            HardwareBuffer.USAGE_COMPOSER_OVERLAY or
            HardwareBuffer.USAGE_FRONT_BUFFER,
    )

The androidx.graphics release notes show how device-specific it is: 1.0.3 fixed full-screen flickers on certain devices below API 33, and 1.0.4 improved compatibility and performance for particular devices.

5. Drawing only what changed, and the part you can’t undo

A front buffer keeps what you drew, so you draw increments. That is simple for ink that only grows. The newest points don’t only grow: Ink’s extruder treats them as volatile (guide 7), reverting and re-adding them on each update, and a predicted tail (guide 6) has to be removed and redrawn on every sample, and you cannot un-draw pixels in a buffer you have already written.

Ink’s API 33 helper (CanvasInProgressStrokesRenderHelperV33) handles that by keeping an off-screen copy of the in-progress strokes. For each update it clips both buffers to the changed region, outset by a few pixels, clears that region of the off-screen buffer, redraws the strokes there, and then copies the region into the front buffer with a replace blend. Its comment gives the reason for doing the clear in the off-screen copy: as two separate operations on the front buffer, the gap between them can be seen, because the display may read the buffer in between and show the background through the stroke.

6. The hard part: the handoff

The stroke is on screen in the front layer. The pen lifts. Now the stroke has to become part of the document, which the View system draws, and the front layer has to be emptied for the next stroke. Try it.

Interactive handoff lab: step through the vsyncs of a handoff from a front-buffered layer to the View system, with four ways of hiding the layer and three ways of clearing it, and see the frames where the stroke is missing or drawn twice. Needs JavaScript.

Each column is one refresh. Front layer is the layer’s own picture, View system is the normal path’s, and On screen is what you see: if neither layer shows the stroke, it blinks out; if both do, it is drawn twice, which you can’t see for an opaque stroke and can for a translucent one, because a pixel covered twice by a stroke of opacity a is covered by 1 − (1 − a)², which is 58% for a highlighter at 35%.

Things to try. Each starts from the lab’s defaults (Hide the front layer: Asked together, two routes; Clear the front buffer: Never; Stroke: Highlighter; A transaction lands after: 2 vsyncs; View system needs: 3) and names every setting it changes.

  • The defaults. The front layer goes at vsync 2 and the View system’s copy arrives at vsync 3, so frame 2 shows nothing. Over View-system times of 1 to 5 vsyncs, 4 of the 5 handoffs glitch: 6 gap frames and 1 double-draw frame in all.
  • Matching delays are luck. Set View system needs to 2, so both updates land on vsync 2: the timeline is clean (the score above it doesn’t move, because it covers every time from 1 to 5). Set it to 1 and the View system’s copy lands first, so frame 1 shows the stroke twice and looks darker. Now set Stroke to Opaque: you can’t see it, and the glitches drop to 3 of 5.
  • Hiding first always blinks. Set Hide the front layer to Hide, then draw and A transaction lands after to 1 vsync: 5 of 5 glitch, 15 gap frames, no double draws.
  • Drawing first trades one failure for the other. Set Hide the front layer to Draw, then hide and A transaction lands after to 1 vsync: 4 of 5 glitch, 6 gap frames and 1 double-draw frame.
  • One frame is clean at every time. Set Hide the front layer to Same frame: 0 of 5. Set Clear the front buffer to Wait 5 frames: still 0 of 5, but the pen can’t draw into a front layer again for 5 frames. Then set View system needs to 6: the buffer is cleared at frame 5, while the layer is still on screen, and frame 5 is empty.
  • A spare layer waits for nothing. From the last setting, set Clear the front buffer to Spare layer: no glitch at 6, and no frames before the pen can draw again.

The rules behind the lab are short. Two updates, hiding the front layer and showing the stroke in the View system, can be asked for in the same breath and still travel different routes: a SurfaceControl transaction, and the window’s frame through the UI thread and render thread. Each takes a number of refreshes to arrive, and if the numbers differ, one is first. The lab takes the View system’s time as 1 to 5 refreshes because that is the range a comment in Ink’s source gives (“about 1-5 vsync periods” through the HWUI pipeline). The cure is not a better guess. It is to make the two updates one update.

How androidx.graphics does it. In CanvasFrontBufferedRenderer the dry scene is not in the View system at all. It is the multi-buffered layer, in the same SurfaceControl tree as the front layer (the front layer is its child), so a single transaction can change both. commit() records the whole scene into a render node, draws it into a buffer on the render thread, and when that is ready:

// library source: CanvasFrontBufferedRenderer.setParentSurfaceControlBuffer (androidx.graphics 1.0.4), trimmed
SurfaceControlCompat.Transaction()
    .setVisibility(frontBufferSurfaceControl, false)
    // Set a null buffer here so that the original front buffer's release callback
    // gets invoked and we can clear the content of the front buffer
    .setBuffer(frontBufferSurfaceControl, null)
    .setVisibility(parentSurfaceControl, true)
    .setBuffer(parentSurfaceControl, buffer, fence) { releaseFence -> … }
    …
    .commit()

One transaction hides the wet layer and sets the dry buffer, and the documentation of Transaction.setBuffer says the compositor treats a transaction as a unit: if several buffers are set in one, none is displayed until all their fences have signalled. That is the Same frame row of the lab. Three rules in the code follow from the design:

  • The scene callback draws the whole scene. onDrawMultiBufferedLayer re-records the layer’s render node every time, and the params it receives are only the ones since the last commit(). Your app keeps the finished strokes and draws them all.
  • Drawing is held back while a commit is in flight. While a commit is counted, renderFrontBufferedLayer queues its parameters instead of drawing them, and flushes them when the commit’s buffer is released.
  • The front buffer is cleared before it is reused. A pending-clear flag makes the next front draw wait on the previous buffer’s release fence and then clear it.

cancel() hides the front layer without committing, and clears the queued parameters. The library says it is for palm rejection, where a stroke starts and an ACTION_CANCEL arrives afterwards (guide 5).

LowLatencyCanvasView. This one draws the wet strokes in a single buffer and, when you call commit(), wraps that same buffer as a bitmap and draws it in the view’s onDraw. To hide the front layer it moves the SurfaceView out of the view’s bounds, and its comment gives the reason it works: since Android N, SurfaceView transformations are synchronous with View hierarchy rendering. So the layer goes at the same frame the bitmap arrives, and the dry pixels are the wet pixels. The price is that the dry content lives in one buffer. Its cancel() only hides the overlay and leaves what was drawn in the buffer, and removing one stroke means clear() and drawing the rest again.

How Jetpack Ink does it. Ink’s dry strokes are drawn by the View system, not in a layer of their own, so that your app can erase, undo, zoom and save them. That puts the two on different surfaces: the front layer belongs to a SurfaceView, and the dry strokes are drawn into the app window by HWUI, the normal View renderer. There are two hops, with different rules. In the first, Ink hands the strokes from the front layer to its own finished-strokes view (FinishedShapesView, a plain View inside InProgressStrokesView) and tells your listener at the same moment; that hop is the rest of this section. The second, from Ink’s view to yours, is guide 7’s removeFinishedStrokes rule, and it is easier: both ends are drawn by the same HWUI frame, so doing the two steps in the same UI-thread loop is enough. Ink picks a helper by API level: CanvasInProgressStrokesRenderHelperV33 on Android 13 and later, …V29 from Android 10 to 12, and …V21, which draws in the View system and has none of the latency savings, below that or when forced.

On Android 13 and later Ink merges the hide into the window’s own frame. SurfaceControlCompat.Transaction.commitTransactionOnDraw takes the transaction and asks the View hierarchy to apply it atomically with the next draw, so the two changes “show up on-screen atomically synced”:

// library source: CanvasInProgressStrokesRenderHelperV33.requestHandoff (androidx.ink 1.0.0), trimmed; [note] comments are mine
SurfaceControlCompat.Transaction()
    .setVisibility(sc, false)
    .setBuffer(sc, null)
    .commitTransactionOnDraw(rootSurfaceControl)
…
mainView.invalidate()
callback.onStrokeCohortHandoffToHwui(strokeCohort)   // [note] Ink adds the cohort to its own view, then tells your listener
…
// [note] the other front buffer takes over, so input can resume right away
callback.onStrokeCohortHandoffToHwuiComplete()

There is a second problem, which is the lab’s last row: the old front buffer can only be cleared once its hiding is really on screen, and nothing tells the app when that happens. Ink’s answer is two front buffers. After a handoff the other, clear, buffer is already on screen above the old one, so the pen keeps drawing immediately. The old one is cleared 500 ms later: its comment says one to five vsyncs is what the hide takes, and that if Android offered a callback or fence for when a transaction is presented, the delay could be based on that. Handoffs are paused until the old buffer is back as the spare, so they are at least 500 ms apart.

On Android 10 to 12 there is one front buffer and FrontBufferToHwuiHandoffV29, which its own comment calls a heuristic: it moves the SurfaceView off screen with the next HWUI draw, waits five postOnAnimation frames, then clears the buffer and moves it back. Its constant comment says the trade-off in both directions: too low and the buffer is cleared before it is off screen, “which will lead to a flicker”; too high and “the beginning of the next stroke may be delayed in rendering”. The class documentation says the approach “almost always” gives a flicker-free handoff. That is the lab’s Wait 5 frames.

The cohort rule. All strokes on screen in the same HWUI frame hand off together, even if one finished earlier in that frame than the other started. The class comment says why: the handoff is synchronised to HWUI frames, while inputs can arrive several times per frame in no guaranteed order. So a stroke can stay in progress a little longer than you expect. Guide 7’s rule has the same two failures at the second hop: removeFinishedStrokes must be called in the same UI-thread loop that makes your view draw the strokes, because otherwise a frame has no stroke, or draws it twice (translucent strokes look more opaque). There both views are in one window, so the same loop does reach the same frame. The lab is about the first hop, where the two updates travel different routes.

7. In an app

You want Use What it leaves to you
Ink’s brushes, geometry and storage InProgressStrokesView The dry layer: draw finished strokes in your view and call removeFinishedStrokes in the same loop (guide 7)
The simplest front layer, and your drawing fits in one buffer LowLatencyCanvasView Erasing, undo and cancel: they mean clear() and a redraw
A scene you own: a front layer plus your own dry layer, with a Canvas CanvasFrontBufferedRenderer The whole scene in onDrawMultiBufferedLayer, on the render thread
The same, with OpenGL GLFrontBufferedRenderer The same, plus the GL state
Your own dry strokes in the View system with your own front layer Copy Ink’s Android 13 design Two front layers, commitTransactionOnDraw, and the delay before clearing
Below Android 10 The View system, with prediction (guide 6) The wait for the frame; unbuffered dispatch there skips batching and resampling, which doesn’t shorten it

The smallest complete example that handles cancel correctly is CanvasFrontBufferedRenderer, because a cancelled stroke never enters the scene:

data class Segment(val x0: Float, val y0: Float, val x1: Float, val y1: Float)

@RequiresApi(Build.VERSION_CODES.Q)
class WetDryInk(private val surfaceView: SurfaceView) {
    private val paint = Paint().apply {
        color = Color.BLACK
        strokeWidth = 6f
        strokeCap = Paint.Cap.ROUND
        isAntiAlias = true
    }

    // Every segment of every finished stroke. Only the render thread touches it.
    private val scene = ArrayList<Segment>()

    private val renderer = CanvasFrontBufferedRenderer(
        surfaceView,
        object : CanvasFrontBufferedRenderer.Callback<Segment> {
            // Render thread. Draw only the new segment: this buffer keeps what it has.
            override fun onDrawFrontBufferedLayer(
                canvas: Canvas, bufferWidth: Int, bufferHeight: Int, param: Segment,
            ) {
                canvas.drawLine(param.x0, param.y0, param.x1, param.y1, paint)
            }

            // Render thread, after commit(). Draw the whole scene: this layer starts empty each time.
            // `params` is only the segments since the last commit, and the library clears it afterwards.
            override fun onDrawMultiBufferedLayer(
                canvas: Canvas, bufferWidth: Int, bufferHeight: Int, params: Collection<Segment>,
            ) {
                scene.addAll(params)
                for (s in scene) canvas.drawLine(s.x0, s.y0, s.x1, s.y1, paint)
            }
        },
    )

    private var last: PointF? = null

    fun onTouch(event: MotionEvent): Boolean {
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                surfaceView.requestUnbufferedDispatch(event)
                last = PointF(event.x, event.y)
            }
            MotionEvent.ACTION_MOVE -> {
                var from = last ?: return true
                for (h in 0 until event.historySize) {
                    val to = PointF(event.getHistoricalX(h), event.getHistoricalY(h))
                    renderer.renderFrontBufferedLayer(Segment(from.x, from.y, to.x, to.y))
                    from = to
                }
                val to = PointF(event.x, event.y)
                renderer.renderFrontBufferedLayer(Segment(from.x, from.y, to.x, to.y))
                last = to
            }
            MotionEvent.ACTION_UP -> {
                last = null
                renderer.commit()      // wet to dry: one transaction hides the front layer
            }
            MotionEvent.ACTION_CANCEL -> {
                last = null
                renderer.cancel()      // hide the front layer; the stroke never joins the scene
            }
        }
        return true
    }

    fun release() = renderer.release(cancelPending = true)
}

Two things the snippet leaves out. The SurfaceView must be in your layout, because the renderer builds its layers under it. And it must be released when the view goes away.

Checkpoint

You should be able to say:

  • Wet ink is the stroke while the pen is down; dry ink is the stroke after it lifts; they are drawn by different paths.
  • Unbuffered dispatch skips the wait for the frame and the resampling, from a touch DOWN or MOVE until UP or CANCEL, and does nothing for drawing that still goes through the View system.
  • A front-buffered layer is one buffer the display reads while you add to it, so it is fast and can tear.
  • Whether it gets an overlay plane is the HWC’s decision, which an app can’t query; the lab’s Overlay plane: No is a model of what losing one would cost.
  • A handoff goes wrong two ways: a gap when the front layer goes first, a double draw when the View system’s copy comes first.
  • Separate updates match only by luck; the fixes are to make them one transaction, or to merge the hide into the window’s own frame.
  • Ink does that on Android 13 and later with commitTransactionOnDraw, two front buffers and a delay of 500 ms before clearing; on Android 10 to 12 it waits five frames.

Why it helps

Symptom What is happening What to do
The ink trails the pen by tens of pixels Samples wait for a frame, and the frame waits for the next refresh Draw the wet stroke in a front layer, with unbuffered dispatch
I called requestUnbufferedDispatch and nothing got faster The drawing still goes through the View system; or the call was made on an event that isn’t a touch DOWN or MOVE, so it did nothing Pair it with a front layer, and call it on the DOWN
The stroke blinks out for a frame when the pen lifts The front layer went before the View system’s copy arrived Make hide and draw one transaction, or use Ink
A highlighter stroke looks darker for a frame The front layer was still showing when the View system’s copy arrived The same
The stroke blinks out a few frames after the pen lifts The front buffer was cleared, on a fixed delay, before the hide was on screen Wait for the hide to be on screen, or use two layers as Ink does on Android 13 and later
Tearing in the stroke The display read the buffer while it was being written Keep the front layer to a small area, as the stylus guide advises
Fast on one tablet, ordinary on another Perhaps the device did not give the layer an overlay plane (an app can’t ask), or it doesn’t support the front-buffer usage and the library fell back Measure on the devices you ship
A cancelled stroke comes back LowLatencyCanvasView.cancel() leaves the pixels in its buffer clear() and redraw the scene, or use CanvasFrontBufferedRenderer, whose cancel() never commits

The map

Topic Code Where
Unbuffered dispatch, app side View.requestUnbufferedDispatch, ViewRootImpl View.java, ViewRootImpl.java
Unbuffered dispatch, native side InputConsumer::consumeBatch InputConsumer.cpp
The reference warning View.requestUnbufferedDispatch reference
Front-buffer renderer CanvasFrontBufferedRenderer source, reference
The view version LowLatencyCanvasView source, reference
The OpenGL version GLFrontBufferedRenderer reference
Transactions SurfaceControlCompat.Transaction source
Ink’s handoff, Android 13 and later CanvasInProgressStrokesRenderHelperV33 source
Ink’s handoff, Android 10 to 12 FrontBufferToHwuiHandoffV29 source
Buffer usage flags HardwareBuffer.USAGE_FRONT_BUFFER, USAGE_COMPOSER_OVERLAY reference
Overlay planes Hardware Composer HAL source.android.com
The stylus guide Low-latency graphics Advanced stylus features
Release notes androidx.graphics releases

Edge cases

  • Resizing and rotation. When the surface’s size or transform changes, CanvasFrontBufferedRenderer releases and rebuilds its layers, and its surface callback redraws the multi-buffered scene by calling onDrawMultiBufferedLayer with no new parameters. That works only if you kept the whole scene.
  • Pausing the app. Ink’s sync is for an immediate shutdown such as onPause, and its documentation warns that if the app is still visible, “the stroke content may flicker”.
  • A whole-screen redraw. The stylus guide says the front buffer is not designed to refresh the whole screen. Use it for the newest stroke, not for panning or zooming a page.
  • Zoom and pan during a stroke. The front layer holds pixels, drawn with the transform of the moment. If the view pans or zooms mid-stroke, the pixels already there don’t move with it.
  • Translucent strokes. Double draws show; opacity also needs the dry layer to draw exactly what the front layer drew, or the handoff will shift the colour even when the timing is right.
  • No overlay plane. In the model the layer is still ahead of the View system, because it doesn’t wait for a frame, but it loses part of the gain (the lab’s Overlay plane: No: 18.7 ms against 10.3 ms with a plane and 33.4 ms through the View system).
  • Older Android. The androidx.graphics renderers need Android 10 (API 29). Below that, Ink draws in-progress strokes in the View system, and the wait for the frame stays.
  • A stalled main thread. Unbuffered samples wait for the thread to be free. A long stall costs a front layer too, once it is longer than the wait for the next scan.
  • Version differences. This is graphics-core 1.0.4 and Ink 1.0.0. On androidx-main at the time of writing, CanvasFrontBufferedRenderer differs from 1.0.4 in explicit-API modifiers, formatting and one new execute method, and the constants quoted here (five frames, 500 ms, commitTransactionOnDraw) are unchanged in Ink’s helpers.

Cross questions

Does requestUnbufferedDispatch make drawing faster?

Not by itself. It makes the app receive samples at once instead of at the start of the next frame, and drawn through the View system the pixel still changes only after a frame. In the lab the two View-system paths are identical. It pays off with something that draws outside the frame, such as a front layer, and the platform's reference says it is not for most apps.

Why not just make onDraw faster?

Because the wait is not in onDraw. A sample waits for the frame to start, the frame waits for the render thread, and the result waits for the next refresh. A cheaper onDraw shortens one of those; the lab's Work per frame changes the time in the frame, and the two refresh waits remain.

Why can't I clear the front layer as soon as the pen lifts?

Because the View system's copy of the stroke has not reached the screen yet. Clearing the front layer first leaves a gap of a few frames where nothing shows the stroke. Both the layer and the View system's copy have to change on the same refresh, which is why Ink merges the hide into the window's own frame.

Why does Ink wait 500 ms, or five frames? Is there a better way?

The hide is a transaction, and the app is not told when it is on screen. Ink's source says that if Android offered a callback or fence for that, the delay could be based on it. Without one it uses a delay long enough for the hide to be on screen: five frames on Android 10 to 12, 500 ms with two layers on Android 13 and later. The cost of the wait is a short delay before the next stroke on Android 10 to 12, and a pause between handoffs on 13 and later.

Why does a highlighter show a double draw but a pen doesn't?

A pixel covered twice by a stroke of opacity a is covered by 1 − (1 − a)². For a = 1 that is 1, the same as covered once. For 35% it is 58%. Ink's documentation says the same about removeFinishedStrokes: translucent strokes appear more opaque when drawn twice.

Is a front layer always faster?

No. It needs the device to give it an overlay plane to be read by the display directly. Without one the model has it composed like another layer, which loses part of the gain (the lab's Overlay plane: No: 18.7 ms against 10.3 ms, and 33.4 ms through the View system). It can also tear, because the display reads the buffer while you write to it, and it suits a small area, not the whole screen.

What is the difference between commit() and cancel()?

commit() draws the finished stroke into the multi-buffered layer and hides the front layer in the same transaction. cancel() hides the front layer and drops the queued parameters, with no commit, so a stroke that turns out to be a palm never joins the scene. In LowLatencyCanvasView the wet and dry pixels share one buffer, so cancel leaves the pixels there until you clear().

How would an eraser work with a front layer?

Not in the front layer. It holds pixels, not strokes, so there is nothing to test or remove. Strokes that can be erased have to live in your own data and be drawn by the dry path, which is why Ink hands finished strokes to your view and why the next guide works on the dry strokes.

Revision: key points

  1. Wet ink is changing and drawn in a front layer; dry ink is final and drawn by the View system.
  2. Unbuffered dispatch collects the batch at once with no resampling (consumeBatchedInputEvents(-1)); you ask on a touch DOWN or MOVE, and it lasts until UP or CANCEL.
  3. Through the View system the pixel changes only after the next frame; unbuffered input alone doesn’t change that.
  4. A front layer is one preserved buffer shown without a fence once visible, above the window (setLayer(Int.MAX_VALUE)), so it is fast and can tear.
  5. An overlay plane composites a buffer in display hardware instead of on the GPU; the HWC decides and an app can’t ask. The library only checks that the buffer usages can be allocated.
  6. A handoff glitches when the front layer’s hide and the View system’s copy land on different refreshes: a gap if the hide is first, a double draw if the copy is.
  7. commit() makes it one transaction; LowLatencyCanvasView moves the SurfaceView in the same frame as the bitmap; Ink uses commitTransactionOnDraw on Android 13 and later.
  8. Ink clears the old front buffer 500 ms after the handoff with two buffers (Android 13 and later), or after five frames (Android 10 to 12); both are delays, not signals.

Cheat sheet

Each concept in a few words.

Concept In a few words
Wet and dry ink Changing and final stroke, drawn by different paths.
Unbuffered dispatch Samples at once: no frame wait, no resampling.
Front buffer A buffer the display reads while you add to it.
Tearing The display shows a half-written buffer.
Overlay plane A display-hardware layer; the HWC decides whether you get one.
Handoff Moving a finished stroke from the front layer to the View system.
Gap Front layer hidden before the dry copy arrives: the stroke blinks out.
Double draw Both showing at once: translucent ink looks darker.
commit() Draws the dry scene and hides the front layer in one transaction.
commitTransactionOnDraw Merges the hide into the window’s next frame (API 33).
Cohort Strokes on screen in the same frame, handed off together.

Search terms that find more: Android front buffer rendering, CanvasFrontBufferedRenderer example, GLFrontBufferedRenderer, SurfaceControl transaction setBuffer, commitTransactionOnDraw, HardwareBuffer USAGE_FRONT_BUFFER, requestUnbufferedDispatch stylus, hardware composer overlay plane.

The fine print

The sources were read from androidx.graphics:graphics-core 1.0.4 and androidx.ink 1.0.0 (the released source jars), and from AOSP main for View, ViewRootImpl, InputEventReceiver and InputConsumer; the snippets compile against those artifacts and were linted at minSdk 26, and the library excerpts (marked library source) are not app code and were not compiled. Nothing here was run on a device. Both labs are TypeScript models whose results follow from the rules written in them, so they have no library test vectors to check against; their tests check the rules, and the pen-to-pixel model against guide 3’s frame timeline. The pen-to-pixel model assumes a render time of 2 ms for each segment, that the panel is scanned once per refresh from top to bottom, and that a layer with an overlay plane is read by the display directly, which is the idea in Ink’s comments (“race the scanline”) and not a measurement. The handoff model takes the transaction delay as 1 or 2 refreshes, and the View system’s time as 1 to 5 refreshes from a comment in Ink’s source. The 5-frame wait counts UI-thread animation callbacks, and the lab counts it in vsyncs, which differ when frames are dropped. There are no millisecond figures for real devices here, and no rate at which Ink’s Android 10 to 12 handoff flickers: its documentation says “almost always” and I haven’t found a published measurement. The frame-rate hint on the front layer is described as the source sets it, not as any device handles it. The pen-to-pixel model follows guide 3 in letting a late frame take every sample that arrived before it started, which can lower the mean when the main thread stalls, and it leaves out the resampling difference of guide 4 between buffered and unbuffered input. Both labs were checked in one desktop browser (Brave): the handoff lab in light and dark at a 1431 px window, including a gap cell and a double-draw cell, and in dark at 386 px; the pen-to-pixel lab in dark at 1431 px and in light at 386 px. The tables and code blocks were only checked for overflowing the page, by script, and the code blocks scroll sideways inside it. Every “Things to try” bullet was re-run from the defaults in the page. Nothing was checked on a phone.

Part of the ink series: 1. Why naive drawing feels bad, 2. Canvas, Paint and Path, 3. Looper, epoll and vsync, 4. From glass to your app, 5. Reading a MotionEvent, 6. Smoothing and predicting the pen, 7. From points to a stroke mesh.

How useful was this guide?

Only the author sees ratings.

Friday's 5 best, plus one guide

The Friday email is on its way. Until then, follow by RSS.