What you’ll study
- The smallest drawing app you can write, and why it feels wrong the moment you use it.
- Twelve separate failures, what causes each, and which layer of Android fixes it.
- The fixes you can make today in a few lines, and the ones that need the rest of this series.
- How to see each failure for yourself, in the ink lab below and on a device.
How it connects
A stroke goes through five places on its way from the glass to a saved file: the touch hardware, Android’s input system, your app’s touch code, the frame pipeline that puts pixels on screen, and storage. Every failure in this guide happens in one of those places, and every later guide in the series fixes one of them. Read this one as the map.
Read it at your level
| Level | Read | You should be able to |
|---|---|---|
| Student | The basics, the ink lab | Draw a line on a Canvas from touch events and say why it looks rough |
| Fresher | + The twelve failures | Name the cause of each artefact you see when you draw |
| Junior | + Fixes you can make today | Add historical samples, curves, round joins and cancel handling to a drawing view |
| Mid | + The map, the cross questions | Say which layer each fix belongs to, and what it costs |
| Senior | + Edge cases | Reason about latency, panels without pressure and several pens at once |
The basics
This is the drawing app almost everyone writes first: a View that adds a line to a Path for every
touch event and asks to be drawn again.
class NaiveInkView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
private val path = Path()
private val paint = Paint().apply {
color = Color.BLACK
style = Paint.Style.STROKE
strokeWidth = 6f
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> path.moveTo(event.x, event.y)
MotionEvent.ACTION_MOVE -> path.lineTo(event.x, event.y)
}
invalidate()
return true
}
override fun onDraw(canvas: Canvas) {
canvas.drawPath(path, paint)
}
}
It works, and it is how the documentation’s own touch examples start. Then you draw a fast circle or write your name, and it doesn’t feel like ink. The line trails behind your finger, curves turn into polygons, corners grow spikes, and on a big board it gets slower the more you write.
Try it: the ink lab
The lab below starts as exactly that naive app, built on the browser’s Pointer Events, which mirror
Android’s MotionEvent closely. Draw fast loops and slow handwriting, then switch a fix on and draw
again beside it: each switch applies to the next stroke, so the page keeps the before and the after.
Watch the counters too. Shaky panel adds the kind of noise a large infrared board or a
finger produces.
Two counters matter. Samples in the last event is how many touch readings arrived bundled into a single event; the naive app uses only the newest one. Ms to draw the last move grows with the drawing until you switch on Draw only what is new.
The twelve failures
| What you see | Why it happens | Where it gets fixed |
|---|---|---|
| The line trails behind the pen | Each event waits for the next frame, then the drawn frame waits to be composited and shown | Input system, frame pipeline |
| Fast curves come out as polygons | Straight lines between samples that are far apart | Your touch code (curves) |
| Detail lost on fast strokes | Only the newest sample in each event is used | Your touch code (historical samples) |
| Spikes and gaps at sharp corners | Default butt caps and miter joins on a thick stroke | Paint settings |
| The app slows as the drawing grows | The whole drawing is redrawn on every move | Frame pipeline (draw only what changed) |
| The line wobbles | Noise from the digitizer, worse with fingers and on large panels | Your touch code (smoothing) |
| Every line has the same width | Pressure is never read | Your touch code (pressure or speed) |
| Width flickers along the stroke | Raw pressure is noisy too | Your touch code (smoothing the width) |
| The palm draws | Every touch is treated as ink | Input system and your code (palm rejection) |
| A palm mark appears, then stays | The system cancels the touch, but the app ignores the cancel | Your touch code (ACTION_CANCEL) |
| A second finger joins or jumps the line | Only pointer 0 is read, so two pointers become one line | Your touch code (per-pointer state) |
| The ink is not under the pen tip | A gap between glass and display (parallax), or a missing transform when zoomed | Hardware, and your coordinate maths |
The rest of this guide takes them in the order a stroke meets them.
1. The line trails behind the pen
Between the pen touching the glass and the pixel lighting up, the stroke passes through the touch controller, the kernel, Android’s input reader and dispatcher, your app’s main thread, the render thread, the system compositor and finally the display. Several of those steps wait for the next frame. The result is a gap you can see: the ink follows the pen instead of coming out of it.
You cannot remove the pipeline, but you can shorten it. Asking for touch events without batching
helps a little (View.requestUnbufferedDispatch,
API 21). Guessing a few milliseconds ahead helps more: Android 14 added
MotionPredictor, and AndroidX
has a motion prediction library for
older releases. The biggest win is drawing the newest part of the stroke outside the normal frame
path, with the AndroidX graphics low-latency classes.
Each of these has its own guide later in the series.
2 and 3. Polygons and lost detail
Touch hardware samples faster than the screen refreshes, so Android bundles several readings into one
ACTION_MOVE. The MotionEvent reference
says it plainly: for efficiency, move events may batch several samples, and the older ones are
available with getHistoricalX() and getHistoricalY(). The naive app reads only event.x and
event.y, the newest sample, and throws the rest away.
Even with every sample, a fast stroke leaves gaps of many pixels between them, and straight lines across those gaps show as corners. A curve through the samples fixes the look (code below).
4. Spikes and gaps at corners
A thick stroke drawn with Paint’s default butt cap and miter join grows a spike at every sharp turn
and a notch where segments meet. Round caps and joins cost almost nothing and remove both. See
Paint: setStrokeCap and
setStrokeJoin. On Android 11 and older, also pass ANTI_ALIAS_FLAG for smooth edges; from Android 12,
Paint() turns it on by default.
5. Slower as the drawing grows
invalidate() followed by drawPath() of one ever-growing Path means every move redraws everything
you have ever drawn. On a phone you may not notice for a while; on a 4K classroom board with a full
lesson of writing you will. The fix is to keep finished strokes somewhere they are not redrawn (a
bitmap, or groups of render nodes) and to draw only the stroke in progress. In the lab, compare
ms to draw the last move with Draw only what is new off and on, after drawing for a while.
6, 7 and 8. Wobble and width
Every digitizer reports some noise; fingers are wide and move while they touch, and large infrared frames estimate position from blocked light beams. A small low-pass filter fixes most of it. The One Euro filter (Casiez, Roussel and Vogel, CHI 2012) is a good default: it smooths slow movement hard and fast movement lightly, so it removes shake without making fast strokes lag. The lab uses it.
Its two settings have to be tuned to your units. With beta 0.007 and a derivative cutoff of 1 Hz,
values common in example code, a fast handwritten loop measured in pixels trails the pen by about
55 px in our tests. The lab uses minCutoff 1 Hz, beta 0.2 and a derivative cutoff of 5 Hz,
which trail the same loop by about 8 px. The authors’ advice is the right method: set beta to zero,
lower minCutoff until slow movement stops shaking, then raise beta until fast strokes stop
lagging.
Width is the other half of looking like ink. A pen that reports pressure gives it through
MotionEvent.getPressure(); many devices don’t. Browsers report a pressure of 0.5 for any device
that cannot measure it (MDN, PointerEvent.pressure),
and many touch panels report a fixed value too. When pressure is missing, width from speed (faster is
thinner) is a reasonable stand-in. Smooth the width as well, or it flickers.
9 and 10. Palms, and the cancel nobody handles
The naive app draws for every pointer, so a resting palm draws too. Stylus devices help: Android can
decide after the fact that a touch was a palm and cancel it. Before Android 13 that arrives as
ACTION_CANCEL; from Android 13 (API 33), ACTION_POINTER_UP or ACTION_CANCEL can also carry
MotionEvent.FLAG_CANCELED, which the reference says is only set on those two actions. An app that
ignores both keeps the palm’s line on the page. Google’s
stylus guide
covers palm rejection in detail.
11. Two fingers, one line
event.x is the first pointer. With two fingers down, a naive ACTION_MOVE handler follows pointer 0
only, and when that finger lifts, the next pointer becomes index 0 and the line jumps across the
page. Every pointer has an index that can change between events and an ID that stays the same
while it is down; keep state per ID. Google’s
multi-touch guide
explains the difference.
12. Ink beside the pen tip
Some of this is hardware: a gap between the touch glass and the display makes the ink appear offset when you look at an angle, which is why pen-first devices laminate the two. The rest is yours: once a canvas can zoom, pan or rotate, every touch point has to go through the inverse of the canvas transform before it is stored.
Checkpoint
Before the fixes, you should be able to say:
- One
ACTION_MOVEcan carry several samples, and the naive app keeps only the newest. - Lag comes from the pipeline between glass and display, not from slow drawing code.
- A pointer’s index can change between events; its ID cannot while it is down.
ACTION_CANCELmeans “undo what this pointer did”, not “the finger lifted”.
Fixes you can make today
These need nothing beyond the platform. Together they fix failures 2, 3, 4, 5, 10 and 11.
Every sample, not just the newest:
MotionEvent.ACTION_MOVE -> {
for (h in 0 until event.historySize) {
path.lineTo(event.getHistoricalX(h), event.getHistoricalY(h))
}
path.lineTo(event.x, event.y)
}
Round ends and joins, smooth edges (the flag only matters before Android 12, where Paint() was
not anti-aliased):
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND
strokeWidth = 6f
}
Curves through the samples. Draw a quadratic curve from the midpoint of the last two samples to the midpoint of the next two, using the sample between them as the control point. The line passes smoothly through every midpoint and never shows a corner:
private var lastX = 0f
private var lastY = 0f
private fun addSample(x: Float, y: Float) {
path.quadTo(lastX, lastY, (lastX + x) / 2, (lastY + y) / 2)
lastX = x
lastY = y
}
Start each stroke with path.moveTo(x, y) and set lastX and lastY to the first sample.
CornerPathEffect is an
even cheaper alternative: it rounds every corner of a path as it is drawn.
Finished strokes into a bitmap, only the live stroke redrawn:
private var done: Bitmap? = null
private var doneCanvas: Canvas? = null
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
done = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
doneCanvas = Canvas(done!!)
}
// On ACTION_UP: doneCanvas?.drawPath(path, paint); path.reset()
override fun onDraw(canvas: Canvas) {
done?.let { canvas.drawBitmap(it, 0f, 0f, null) }
canvas.drawPath(path, paint)
}
A bitmap is the simplest version; it loses the strokes as objects, so undo and erase get harder. Later guides keep strokes as data and group the finished ones into render nodes instead.
One stroke per pointer ID, and cancels undone:
private val live = mutableMapOf<Int, Path>()
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
val i = event.actionIndex
live[event.getPointerId(i)] = Path().apply { moveTo(event.getX(i), event.getY(i)) }
}
MotionEvent.ACTION_MOVE -> for (i in 0 until event.pointerCount) {
val stroke = live[event.getPointerId(i)] ?: continue
for (h in 0 until event.historySize) {
stroke.lineTo(event.getHistoricalX(i, h), event.getHistoricalY(i, h))
}
stroke.lineTo(event.getX(i), event.getY(i))
}
MotionEvent.ACTION_POINTER_UP -> {
val id = event.getPointerId(event.actionIndex)
val cancelled = Build.VERSION.SDK_INT >= 33 &&
(event.flags and MotionEvent.FLAG_CANCELED) != 0
live.remove(id)?.let { if (!cancelled) commit(it) }
}
MotionEvent.ACTION_UP -> live.remove(event.getPointerId(0))?.let(::commit)
MotionEvent.ACTION_CANCEL -> live.clear() // a palm or a gesture took over: drop the strokes
}
invalidate()
return true
}
commit() is wherever finished strokes go, such as the bitmap above. Note getHistoricalX(i, h):
the two-argument form reads the history of pointer i, which you need once more than one pointer is
down.
Ask for touch without batching, as each stroke starts:
MotionEvent.ACTION_DOWN -> {
requestUnbufferedDispatch(event)
// ...
}
This delivers samples as soon as they arrive instead of once per frame. It lowers lag a little and costs more wake-ups, so use it only on the drawing view.
Why the rest needs its own guides
Smoothing, prediction, low-latency drawing, an eraser that stays fast on a full board and several
students writing at once each need more than a snippet, and each has a guide in this series: the
heartbeat of a frame, the path from glass to your app, reading a MotionEvent fully, smoothing and
prediction, turning points into a stroke mesh, low latency, the eraser, many hands on one board, and
big boards on slow chips.
If you want to skip ahead, Jetpack’s Ink library does much of this for you: brushes, stroke geometry, low-latency rendering and storage. The series explains what it does inside, so you know what you are getting and what to do on a device it doesn’t suit.
Edge cases
- Panels without pressure. Large infrared boards often report no real pressure. Plan for width
from speed or from contact size (
getTouchMajor()), not fromgetPressure(). - A stylus and a finger at once. Check
getToolType(i)per pointer:TOOL_TYPE_STYLUSfor the pen tip,TOOL_TYPE_ERASERfor the eraser end,TOOL_TYPE_FINGERfor a finger. Deciding that fingers pan and pens draw removes most palm problems on pen devices. - The view is in a scrolling parent. The parent can steal the touch after a few pixels and send
you
ACTION_CANCEL. Callparent.requestDisallowInterceptTouchEvent(true)when a stroke starts. - Hover. Pens report
ACTION_HOVER_MOVEbefore they touch. A drawing app can show where the ink will land; it should not draw.
Cross questions
Your drawing app looks fine when you draw slowly and turns jagged when you draw fast. Name two causes.
It reads only the newest sample of each batched ACTION_MOVE, and it joins samples with straight lines. Read the historical samples and draw curves through them.
Why can't you fix touch lag by making onDraw() faster?
Most of the lag is waiting: for the next frame, for the compositor, for the display. Fast drawing code does not shorten those waits. Prediction and drawing outside the normal frame path do.
A second finger lands while the first is drawing, then the first lifts. The line jumps. Why?
The code tracks pointer index 0. When the first finger lifts, the second becomes index 0. Track strokes by getPointerId(), which stays the same for as long as that pointer is down.
What should your view do with ACTION_CANCEL?
Treat it as "this touch should not have happened": drop the stroke in progress. It arrives when a parent intercepts the gesture or the system decides the touch was a palm.
On Android 13, what does FLAG_CANCELED on ACTION_POINTER_UP tell you?
That this one pointer was cancelled, for example a palm, while other pointers stay down. Drop that pointer's stroke and keep the others.
Why does a drawing app get slower the longer someone writes, and what is the simplest fix?
Every move redraws every stroke. Draw finished strokes once into a bitmap (or group them into render nodes) and redraw only the stroke in progress.
Revision: key points
- A naive drawing app fails in twelve ways, in five places: hardware, input system, your touch code, the frame pipeline and storage.
ACTION_MOVEbatches samples; read them withgetHistoricalX()andgetHistoricalY().- Straight lines between samples look like polygons; draw curves through the midpoints.
- Round caps and joins fix corners almost for free;
Paint()is anti-aliased by default from Android 12. - Redrawing everything on every move makes the app slower as the drawing grows; keep finished strokes apart.
- Lag is mostly waiting in the pipeline; it needs prediction and low-latency drawing, not faster
onDraw(). - Track strokes per pointer ID, and undo them on
ACTION_CANCELorFLAG_CANCELED(API 33). - Many panels report no real pressure; plan for width from speed or contact size.
Cheat sheet
Each concept in a few words.
| Concept | In a few words |
|---|---|
| Samples in history | One MOVE carries several samples; read them all. |
| Pointer ID | Names a finger while it is down; the index can change. |
| Cancel | Undo what that pointer did; it is not a lift. |
| Polygon look | Straight chords between far samples; curve through midpoints. |
| Round cap and join | Smooth ends and corners almost for free. |
| Anti-aliasing | Soft edges; Paint() has it by default from Android 12. |
| Redraw cost | Redrawing every stroke on every move slows as the drawing grows. |
| Baked bitmap | Finished strokes drawn once; only the live stroke is redrawn. |
| Latency | Time stuck in the pipeline; a faster onDraw() doesn’t fix it. |
| Panel pressure | Often a constant 0.5; take width from speed or contact size. |
Read next
MotionEventreference: actions, pointers, history and axes- Track touch and pointer movements and Handle multi-touch gestures
- Stylus input and advanced stylus features
PaintandCornerPathEffectMotionPredictor, and the AndroidX input, graphics and ink libraries- The One Euro filter, with the paper and code in many languages
- In the browser:
getCoalescedEvents()andgetPredictedEvents(), the web’s versions of historical samples and prediction - Under Android: the Linux multi-touch protocol, and where AOSP batches and resamples touch for each frame,
InputConsumer.cpp
Search terms that find more: motion event batching, touch resampling, front buffer rendering, One Euro filter, palm rejection, pointer id vs index.
The fine print
API levels are from the Android reference pages as of November 2026: getActionMasked() API 8,
requestUnbufferedDispatch(MotionEvent) API 21, FLAG_CANCELED API 33, MotionPredictor API 34.
The ink lab runs on the browser’s Pointer Events, which behave like Android’s MotionEvent but are not
the same code: prediction and batched samples depend on the browser, and the switches it cannot offer
are greyed out.
First guide of the ink series. The rest of the internals series: why read internals, launch modes, WorkManager, ViewModel, process death and saved state.