What you’ll study
- Why a list of points is not yet a stroke: it has corners, noise and no width.
- Making a centreline: connect the dots, a Catmull-Rom spline through them, or the time-window average Jetpack Ink uses.
- Width: from pressure, from speed, or fixed, and why a touch panel’s pressure is no use.
- From a centreline and a width to triangles: offset two sides, stitch them, and see why a tight turn folds the mesh.
- Fewer vertices: Ramer-Douglas-Peucker, and what the brush’s
epsilonmeans. - How Ink holds the result (
Mesh,PartitionedMesh) and draws it.
How it connects
Guide 6 ended with cleaned-up points and a temporary predicted tail.
This guide turns those points into the shape that is drawn. The next one, on low-latency drawing, draws that shape without waiting
for a frame, and the eraser guide that follows tests an eraser against the mesh built here. Guide 2
covered drawing a Path; this is what you reach for when a Paint’s single width is not enough.
Read it at your level
| Level | Read | You should be able to |
|---|---|---|
| Student | The basics, the lab | Say why a list of points is not a stroke, and what a triangle mesh is |
| Fresher | + The high level, curves and width | Explain what a spline through noisy points does, and why a panel’s pressure can’t set a width |
| Junior | + Outlines, simplification | Build a strip of triangles along a path, and say why a sharp turn folds it |
| Mid | + The mesh, drawing it | Say what a Stroke exposes to an app, and when Ink draws a mesh and when it draws a path |
| Senior | + Edge cases, cross questions | Reason about what the input model, epsilon and the renderer each cost on a given device |
The basics
A stroke on screen is a shape, a region with an edge. What a pen gives you is a list of points. Three jobs lie between the two.
- A curve. Draw straight lines between the points and every sample is a corner. A fast stroke on a slow digitizer has points far apart, so the corners show. Noise adds small wobbles on top.
- A width. A point has no thickness. A line gets one from the brush size, from how hard the pen presses, or from how fast it moves.
- Triangles. A GPU draws triangles, and an eraser (guide 9) tests against shapes. So the outline of the line has to be cut into triangles: a mesh.
You don’t always need the third job. A Paint has a single stroke width, so a line of constant width can be drawn as a Path (guide 2), and that
is often the right answer. A line whose width follows pressure can’t, because the width changes along it: it has to be drawn as a filled shape,
either its outline or the triangles inside it. A mesh also gives each stroke a size you can count, a bounding box and edges you can test.
Jetpack Ink, Google’s freehand-drawing library, builds a mesh for every stroke. This guide builds the same stages from scratch, then shows what Ink does at each one.
Try it: the stroke mesh lab
The same noisy stroke as the last guide, turned into a mesh. The dashed line is the true path, the dots are the raw samples, the thin line is the centreline, and the green triangles are the mesh. A red triangle is folded: its corners come in the wrong order, so it faces backwards. Zoom and Look at move a close-up along the stroke, and every number is measured against the true path.
Things to try. Each starts from the lab’s defaults (sliding window, 120 Hz, 1 px of noise, pen, pressure width, size 8, round joins, epsilon 0.25 px, 3× zoom) and names every setting it changes. The lab shows one noise sequence, so its numbers differ a little from the tables below, which are means of 8.
- A spline helps clean data. Set Centreline to Raw polyline, Report rate to 60 Hz and Noise to 0. The error is 0.74 px. Switch to Catmull-Rom: 0.38 px. Switch to Sliding window: 1.17 px, worse than the raw line, with no noise at all, because the window rounds every turn.
- A spline does not help noisy data; the window does. Set Report rate to 240 Hz and Noise to 2 px. The raw polyline is 1.68 px from the true path and Catmull-Rom 1.79 px; the sliding window is 0.90 px.
- Noise folds the mesh. Set Width from to Constant, Size to 7, Joins to Plain, Report rate to 240 Hz and Noise to 2 px. The raw polyline has 62 folded triangles of 457, Catmull-Rom 358 of 1290, and the sliding window 17 of 285. The red ones are the outline folding over itself at tiny reversals.
- Epsilon is the size of the mesh. Set Centreline to Catmull-Rom, Width from to Constant, Size to 7, Joins to Plain, Report rate to 240 Hz and Noise to 1 px. The outline starts as 3840 triangles before it is simplified. At Epsilon 0.05 px it keeps 1804 of them; at 0.25 px, 1009; at 2 px, 328. Zoom to 6× at 2 px and the curve is visibly a polygon.
- Round joins add vertices at a corner. Set Centreline to Raw polyline, Report rate to 60 Hz, Noise to 0, Width from to Constant, Size to 14, Zoom to 6× and Look at to 500 ms. With Plain joins the outside of the corner is a flat cut and the mesh has 101 triangles; with Round it is an arc and has 124.
- Panels have no pressure. Set Device to Panel (0.5). With Width from Pressure the width now comes from speed; with Ink pen it stays one size. With Pen and Ink pen, only the middle of the stroke, where the pressure passes 0.8, gets wider.
The lab runs a TypeScript model. The sliding window and the simplification are ports of Ink’s source, checked against the library’s own test cases; the offsetting and stitching are the simple method this guide starts with, not Ink’s tip-shape sweep. The section on the sliding window says how.
The high level
| Stage | What it does | What it costs |
|---|---|---|
| Input model | Averages the raw samples over a short time window, and adds points where samples are far apart | Cuts tight corners; the newest half window is provisional and gets redrawn |
| Curve | Joins the points with a spline instead of straight lines | A spline through noisy points follows the noise, and makes many more points |
| Width | Sets a line width at each point, from pressure, speed or a constant | A touch panel’s pressure is a constant, so it can’t set width |
| Outline | Moves each point left and right by half the width | Folds where the path turns tighter than the line is wide |
| Stitch | Joins the left and right outlines with triangles | Two triangles per pair of vertices |
| Simplify | Drops outline vertices that change the shape by less than epsilon |
Corners flatten if epsilon is large |
| Package | Stores the triangles in meshes, and the meshes in a PartitionedMesh |
A Mesh has 16-bit indices, so a long stroke is several meshes |
| Draw | Canvas.drawMesh on Android 14 and later, otherwise a path of the outline |
The mesh path needs a hardware-accelerated canvas |
The low level
Source excerpts are from Jetpack Ink: the Kotlin API at version 1.0.0, and the C++ core at the jetpack-1.0.0 tag of
google/ink, trimmed with …. Where the core’s current main differs, the text says so. Links are in The map.
1. A curve through the points: Catmull-Rom
The first fix for corners is a Catmull-Rom spline: a curve that passes through every point, with its direction at each point set by the points on either side. For the four points P0 to P3, the part of the curve from P1 to P2 is the cubic Bézier curve with control points
c1 = P1 + (P2 - P0) / 6
c2 = P2 - (P3 - P1) / 6
That is the uniform spline, which assumes the points are evenly spaced. When they are not, it can loop or overshoot. The centripetal spline spaces its
knots by the square root of the distance between points. Yuksel, Schaefer and Keyser’s paper introduced it, and as Wikipedia summarizes the result, it never
forms a loop or a cusp within a segment and follows the points more tightly. The lab uses the centripetal one. For a Path, the uniform version is a few lines:
/** A smooth Path through every point, as one cubic Bézier per gap (a uniform Catmull-Rom spline). */
fun catmullRomPath(xs: FloatArray, ys: FloatArray, count: Int): Path {
val path = Path()
if (count == 0) return path
path.moveTo(xs[0], ys[0])
for (i in 0 until count - 1) {
val before = maxOf(i - 1, 0) // the first and last points stand in for their missing neighbours
val after = minOf(i + 2, count - 1)
path.cubicTo(
xs[i] + (xs[i + 1] - xs[before]) / 6f, ys[i] + (ys[i + 1] - ys[before]) / 6f,
xs[i + 1] - (xs[after] - xs[i]) / 6f, ys[i + 1] - (ys[after] - ys[i]) / 6f,
xs[i + 1], ys[i + 1],
)
}
return path
}
What it buys, from the lab (the mean over 8 noise sequences; the error is the distance from the true path):
| Report rate, noise | Raw polyline | Catmull-Rom | Sliding window (section 2) |
|---|---|---|---|
| 60 Hz, none | 0.74 px | 0.38 px | 1.17 px |
| 60 Hz, 1 px | 1.09 px | 0.95 px | 1.37 px |
| 120 Hz, 2 px | 1.68 px | 1.83 px | 1.29 px |
| 240 Hz, none | 0.04 px | 0.01 px | 0.57 px |
| 240 Hz, 2 px | 1.67 px | 1.79 px | 0.98 px |
| 240 Hz, 3 px | 2.54 px | 2.69 px | 1.32 px |
On clean data at a slow report rate, the spline halves the error: the curve between two samples is better than a chord. With noise it does nothing for you. It passes through every noisy sample, so it is as far from the true path as the polyline is, a little further, and it makes eight points for every one (8 per gap in the lab). A spline joins points; it doesn’t clean them.
2. What Ink does instead: a sliding window over time
Ink doesn’t use a spline for the centreline. (Its only Bézier curves are the easing functions that shape brush behaviors.) In version 1.0.0, the Kotlin BrushFamily.DEFAULT_INPUT_MODEL is a SlidingWindowModel, and the stock brushes
(StockBrushes.pressurePen(), marker() and the others) are all built with one. (The model classes are marked restricted and experimental in 1.0.0, so an app normally gets
the window model by using a stock brush.) That library version also ships a spring-based model and an experimental “naive” one; the core’s main has since removed the spring
model and renamed the naive one to PassthroughModel, which passes the raw inputs through for an app that wants to do its own modeling.
The window model replaces each point with the average of the raw path over a window of time, centred on the point. The raw path is read as straight lines between samples, so the average is a trapezoid integral. The defaults are a 20 ms window and an upsampling period of 1/180 second:
// brush_family.h: SlidingWindowModel
Duration32 window_size = Duration32::Millis(20);
Duration32 upsampling_period = Duration32::Seconds(1.0 / 180.0);
// sliding_window_input_modeler.cc: ModelUnstableInputPosition(), trimmed
Duration32 half_window_size =
std::min(half_window_size_,
std::min(elapsed_time - sliding_window_.First().elapsed_time,
sliding_window_.Last().elapsed_time - elapsed_time));
Duration32 start_time = elapsed_time - half_window_size;
Duration32 end_time = elapsed_time + half_window_size;
…
// Integrate each field over each raw-input-to-raw-input interval inside the window…
Point position = Point::FromOffset(integrals.position_dt / dt);
if (IsWithinEpsilonOfLastInput(modeled_inputs, position)) {
return;
}
Four things follow, and the lab shows the first two:
- It is counted in time, not samples. The window is the same 20 ms on every device, which is five samples at 240 Hz and about one at 60 Hz (guide 6’s cross question about window length). So the span is the same but how much it smooths is not: at 60 Hz it barely smooths, and its corner-cutting still costs. In the table above it is worse than the raw samples at 60 Hz, even with 1 px of noise. From 2 px at 120 Hz it clearly wins.
- It cuts corners. An average rounds anything sharper than the window. At 240 Hz with no noise at all its worst point is 2.7 px from the true path, against 0.2 px for the raw samples. Ink’s own test shows it: three raw points tracing an L, 10 ms apart, with a 10 ms window and one modeled point per millisecond, gives points that round the corner instead of turning it (the test’s expected values):
| Modeled point (1 ms apart) | Position |
|---|---|
| 5 | (50, 0) |
| 6 | (59.5, 0.5) |
| 8 | (75.5, 4.5) |
| 11 | (92, 18) |
| 13 | (98, 32) |
| 15 | (100, 50) |
- The ends stay put. The window shrinks near the start and end, symmetrically, down to nothing at the very first and last sample, so the finished stroke reaches the last position the pen was at.
- The newest part is provisional. A modeled point needs raw samples on both sides. Until they arrive, it is computed from a smaller window, and Ink marks it unstable and recomputes it on the next call. A point becomes stable once it is more than half a window older than the newest real sample:
// MarkStableModeledInputs()
while (state.stable_input_count < state.real_input_count &&
modeled_inputs[state.stable_input_count].elapsed_time + half_window_size_ <
state.total_real_elapsed_time) {
++state.stable_input_count;
}
Upsampling is the other half. When two raw samples are further apart than the upsampling period, Ink inserts evenly spaced modeled points between them (at most 100
per gap). At 60 Hz that triples the points; at 240 Hz, faster than 180 Hz, it adds none. A modeled point within the brush’s epsilon of the one before is
dropped, so a pen held still doesn’t pile up points. The predicted samples of guide 6 are fed through the same window and then thrown away on
the next call, which is why Ink’s input to the mesh builder is “real points that are stable, then real points that are provisional, then predicted ones”.
3. Width: pressure, speed, or neither
A point has no width until a rule gives it one. Three rules are in the lab:
- Constant. The brush size, everywhere.
- Pressure. Guide 1’s rule: width from pressure when the device really reports it, from speed when it doesn’t (faster, thinner).
- Ink pen. Only the pressure term of Ink’s stock
pressurePen().
A brush in Ink doesn’t map pressure straight to width. It has a list of behaviors, each turning an input (pressure, speed, direction, acceleration) into a multiplier on one property, with a range, a clamp and a response time that smooths the input. This is the stock pen’s pressure term, from the library:
BrushBehavior(
Source.NORMALIZED_PRESSURE,
Target.SIZE_MULTIPLIER,
sourceValueRangeStart = 0.8f,
sourceValueRangeEnd = 1f,
targetModifierRangeStart = 1.0f,
targetModifierRangeEnd = 1.5f,
OutOfRange.CLAMP,
responseTimeMillis = 30L,
enabledToolTypes = setOf(InputToolType.STYLUS),
)
That is library source, not something an app can write: in 1.0.0 BrushBehavior and its sources and targets are restricted and experimental, and lint rejects a call from app code. The
stock pen is the way to get it. Read it as: below a pressure of 0.8 the width is the brush size; from 0.8 to 1.0 it grows to 1.5 times; the input is smoothed over 30 ms; and it applies
to a stylus only. The same pen has other terms that make the line thicker or thinner with the distance still to travel, the direction, and the lateral
acceleration. Two lessons are in that one excerpt:
- Pressure is a signal to shape, not a width. Most of a light stroke is at the base size.
- Touch is not a pen. A browser reports pressure 0.5 for anything that can’t sense it, and an infrared panel is one of those. The stock pen applies its pressure term to a stylus only, and with the lab’s Panel device and Pressure rule the width comes from speed instead (guide 1’s fallback). Check the tool type before you trust a pressure (guide 5).
The same stock behavior list has one more term that matters here: predictionFadeOutBehavior lowers the opacity from 1 toward 0.3 as the predicted input runs from 0 to 24 ms
ahead, so a wrong guess is faint. The fade doesn’t start until the predicted points have travelled one and a half brush sizes, and is complete at two. That is guide 6’s advice to draw the tail
fainter than the ink, as a brush setting.
4. From a centreline and a width to triangles
Take the centreline points, and for each one find the direction the line is going, which is the direction from the previous point to the next. Its normal points left. Put one vertex at the point plus the radius along the normal and one at the point minus it: a left and a right vertex. Join them with two triangles per step:
L0 ---- L1 ---- L2 left side of the line
| \ | \ |
| \ | \ | each gap is two triangles,
| \ | \ | (R0, R1, L0) and (R1, L1, L0)
R0 ---- R1 ---- R2 right side of the line
A line of n points makes 2n vertices and 2(n - 1) triangles. This is a triangle strip; the code below stores it as an indexed triangle list (three indexes per triangle), which is how Ink stores its mesh too. The loop is short:
class Strip(val xs: FloatArray, val ys: FloatArray, val triangles: IntArray)
/** A strip along a centreline: vertex 2i is on the normal's side of point i and vertex 2i + 1 on the other. */
fun strip(px: FloatArray, py: FloatArray, radius: FloatArray): Strip {
val n = px.size
if (n < 2) return Strip(FloatArray(0), FloatArray(0), IntArray(0))
val xs = FloatArray(2 * n)
val ys = FloatArray(2 * n)
for (i in 0 until n) {
val dx = px[minOf(i + 1, n - 1)] - px[maxOf(i - 1, 0)] // the direction of travel at point i
val dy = py[minOf(i + 1, n - 1)] - py[maxOf(i - 1, 0)]
val length = hypot(dx, dy).takeIf { it > 0f } ?: 1f
val nx = -dy / length // the normal on the left in a y-up frame (on screen, with y down, it points right)
val ny = dx / length
xs[2 * i] = px[i] + nx * radius[i]
ys[2 * i] = py[i] + ny * radius[i]
xs[2 * i + 1] = px[i] - nx * radius[i]
ys[2 * i + 1] = py[i] - ny * radius[i]
}
val triangles = IntArray(6 * (n - 1))
for (i in 0 until n - 1) {
val left = 2 * i
val right = 2 * i + 1
triangles[6 * i + 0] = right
triangles[6 * i + 1] = right + 2
triangles[6 * i + 2] = left
triangles[6 * i + 3] = right + 2
triangles[6 * i + 4] = left + 2
triangles[6 * i + 5] = left
}
return Strip(xs, ys, triangles)
}
/** True when a triangle's corners are in the wrong order: the strip has folded over itself. */
fun Strip.isFolded(triangle: Int): Boolean {
val (a, b, c) = Triple(triangles[3 * triangle], triangles[3 * triangle + 1], triangles[3 * triangle + 2])
val area = (xs[b] - xs[a]) * (ys[c] - ys[a]) - (ys[b] - ys[a]) * (xs[c] - xs[a])
return area <= 0f
}
The strip is only right while the path is gentle. Where it turns tighter than the line is wide, the inside vertices overtake each other and the triangles between
them come out backwards: the red triangles in the lab. On the outside of the same turn the two offsets leave a gap. A round join fills it
by putting an arc of vertices around the outside of the turn: the arc has the line’s radius, and its vertices are close enough that the chord between
neighbours is never more than epsilon from the true arc. For a turn of angle θ on radius r, a chord covering the angle θ is r (1 - cos(θ / 2)) from the arc, so
each step is at most 2 acos(1 - epsilon / r). The lab’s Round joins do this; with Plain joins you can see the gap. Rounding the outside does nothing for the inside, and the
red triangles stay. The lab also shows that noise causes folds: a noisy centreline turns left and right at every sample, so its points are
full of tiny reversals. At 240 Hz and 2 px of noise, the raw polyline folds 84 triangles on average, and the sliding-window centreline 16 (a line 7 px wide, plain joins, before simplification, 8 sequences). The lab simplifies the outline as well, which removes some folds, so its counts are lower.
Ink does not offset a centreline. Its extruder keeps a tip shape at every point, a circle with the brush size as its diameter by default, whose size and shape behaviors can change along the stroke, and connects
each shape to the next by the lines tangent to both, “as though each tip shape smoothly morphs into the next” in the extruder’s own words. For two circles of radii r0 and r1 that are
D apart, the outer tangent has a normal u with u · d = (r0 - r1) / D along the direction d between the centres; that is the offset when the radius changes along the stroke,
and it falls back to the plain offset when the radius is constant. When one shape contains the next there are no tangents at all, and the extruder checks for that case (kNoTangentsFirstContainsSecond).
The extruder appends the left and right vertices to a mesh as they arrive and judges each proposed triangle by its winding. Folded triangles are the sign Ink looks for. Its design notes
(line_mesh_generation.md) describe one fast path, for a counter-clockwise triangle with no intersection in progress, and seven slow cases for a turn tighter than the line is
wide. In those, Ink rejects vertices that haven’t moved far enough, moves outline vertices out of the way within a “reposition budget”, and rewrites the triangles it already added, with
an undo stack in case the pen turns back. The result is a mesh with no backwards triangles for the common cases, not a rule that a turn can’t be tight.
5. Fewer vertices: Ramer-Douglas-Peucker
A stroke drawn at 240 Hz has far more vertices than its shape needs. Ramer-Douglas-Peucker (Ramer 1972, Douglas and Peucker 1973) drops the ones that don’t matter: draw a straight
segment from the first point to the last, find the point farthest from it, and if that point is further than epsilon keep it and do the same on each half; if not, drop everything between.
This is Ink’s SimplifyPolyline, nearly line for line:
// simplify.cc, trimmed
void SimplifyPolylineInterior(Segment seg, …interior_begin, …interior_end, float epsilon, …output) {
if (std::distance(interior_begin, interior_end) < 1) return;
// Find the point that is farthest from the segment.
…
if (max_distance > epsilon) {
SimplifyPolylineInterior(Segment{seg.start, farthest_point->position}, interior_begin, farthest_point, epsilon, output);
output.push_back(*farthest_point);
SimplifyPolylineInterior(Segment{farthest_point->position, seg.end}, farthest_point + 1, interior_end, epsilon, output);
}
}
Ink’s own test uses a 14-point line. The number of points kept depends on epsilon:
epsilon |
Points kept of 14 |
|---|---|
| 0.5 | 13 |
| 1.25 | 7 |
| 3 | 3 |
The distance is to the segment, not the infinite line through it. Written without recursion, so a long stroke can’t overflow the stack:
/** The indexes of the points to keep: Ramer-Douglas-Peucker. */
fun simplify(xs: FloatArray, ys: FloatArray, epsilon: Float): List<Int> {
val n = xs.size
if (n < 3) return List(n) { it }
val keep = BooleanArray(n)
keep[0] = true
keep[n - 1] = true
val pending = ArrayDeque<IntArray>()
pending.addLast(intArrayOf(0, n - 1))
while (pending.isNotEmpty()) {
val (from, to) = pending.removeLast()
var farthest = -1
var farthestDistance = 0f
for (i in from + 1 until to) {
val d = distanceToSegment(xs[i], ys[i], xs[from], ys[from], xs[to], ys[to])
if (d > farthestDistance) {
farthestDistance = d
farthest = i
}
}
if (farthest >= 0 && farthestDistance > epsilon) {
keep[farthest] = true
pending.addLast(intArrayOf(from, farthest))
pending.addLast(intArrayOf(farthest, to))
}
}
return keep.indices.filter { keep[it] }
}
private fun distanceToSegment(px: Float, py: Float, ax: Float, ay: Float, bx: Float, by: Float): Float {
val dx = bx - ax
val dy = by - ay
val lengthSquared = dx * dx + dy * dy
if (lengthSquared == 0f) return hypot(px - ax, py - ay)
val u = (((px - ax) * dx + (py - ay) * dy) / lengthSquared).coerceIn(0f, 1f)
return hypot(px - (ax + u * dx), py - (ay + u * dy))
}
In Ink it runs on the outline, once per side, and not on the input points, and it runs as the stroke grows, on the newest vertices of each side. Its
threshold is the brush epsilon (the extruder’s GetSimplificationThreshold(brush_epsilon) returns brush_epsilon, and so does its maximum arc chord height), so one number
sets how fine the whole mesh is. The extruder skips a simplification that would leave a gap larger than a travel limit, or that would make an earlier simplification wrong. The
Brush documentation says epsilon is in the units of the stroke’s coordinate system, that lower values mean higher fidelity “at the cost of somewhat higher memory usage”, and that
0.1 physical pixels at the default zoom is a good starting point. If the app zooms, it should scale epsilon with the zoom, which the InProgressStrokesView documentation also says.
The lab’s Epsilon slider does both jobs at once, as Ink does. At 0.05 px the outline keeps most of its vertices. Raise it and the triangle count drops; at 2 px a smooth curve starts to look like a polygon.
6. The result: Mesh and PartitionedMesh
A finished Stroke holds its shape as a PartitionedMesh. Its documentation: a complex shape expressed as a set of triangles, divided into render groups (one for each brush coat), each
group holding one or more meshes of the same format, plus optional outlines, polylines through the vertices that are used for path drawing. It exists because a single Mesh has
16-bit indices (Mesh.rawTriangleIndexData is a ShortBuffer). The documentation says the partitions let Ink create strokes with more than 2^16 triangles, which “must be rendered in multiple passes”.
It also carries a spatial index, built the first time something needs it, for example by computeCoverage, the intersection test that the eraser in guide 9 uses.
The meshes themselves are not for apps to read. In 1.0.0 the Mesh class, PartitionedMesh.renderGroupMeshes() and the vertex and index buffers of an InProgressStroke are all
marked @RestrictTo(LIBRARY_GROUP), and lint reports a call as a RestrictedApi error. What an app can ask a finished stroke is public: its bounding box, its
outlines, and coverage by a shape. The renderer, which is inside the library, is what reads the mesh:
/** How big a finished stroke's shape is, from the public API only: one line per render group (brush coat). */
fun describe(stroke: Stroke): String {
val shape = stroke.shape
return buildString {
for (group in 0 until shape.getRenderGroupCount()) {
val outlines = shape.getOutlineCount(group)
val vertices = (0 until outlines).sumOf { shape.getOutlineVertexCount(group, it) }
append("group $group: $outlines outline(s), $vertices outline vertices\n")
}
append("bounds: ${shape.computeBoundingBox()}")
}
}
An InProgressStroke, the stroke while it is being drawn, is updated in place as new inputs arrive. It reports the box its mesh covers (populateMeshBounds) and the region
that changed since the last frame (populateUpdatedRegion), so a renderer can redraw only that part.
7. Drawing it
CanvasStrokeRenderer.create() picks a strategy from the device. This is the library’s choice, trimmed:
// CanvasStrokeUnifiedRenderer
private val rendererPreferences: List<Lazy<CanvasStrokeCoatRenderer>> = buildList {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && !forcePathRendering) {
add(lazy { CanvasMeshRenderer(textureStore) })
}
add(lazy { CanvasPathRenderer(textureStore) })
}
On Android 14 and later it prefers Canvas.drawMesh, which its comment calls both more performant and more fully featured. Otherwise it draws a Path built from the
outlines with Canvas.drawPath. The mesh path needs a hardware-accelerated canvas: the library checks canvas.isHardwareAccelerated and, if not, tries a test mesh and falls back if that throws. A
finished stroke is drawn with the renderer:
class StrokeLayer(context: Context) : View(context) {
private val renderer = CanvasStrokeRenderer.create()
private val identity = Matrix()
val finished = mutableListOf<Stroke>()
override fun onDraw(canvas: Canvas) {
for (stroke in finished) renderer.draw(canvas, stroke, identity)
}
}
For the stroke being drawn, Ink has a view that takes the input and draws the stroke in progress, with low-latency rendering where the system supports it. You give it each
MotionEvent, and the predicted event from guide 6, and it handles the model, the mesh and the drawing:
implementation("androidx.ink:ink-authoring:1.0.0")
implementation("androidx.ink:ink-brush:1.0.0")
implementation("androidx.ink:ink-strokes:1.0.0")
implementation("androidx.ink:ink-rendering:1.0.0")
implementation("androidx.ink:ink-geometry:1.0.0")
implementation("androidx.input:input-motionprediction:1.0.1")
class InkView(context: Context) : FrameLayout(context), InProgressStrokesFinishedListener {
private val layer = StrokeLayer(context) // finished strokes, drawn by the renderer above
private val inProgress = InProgressStrokesView(context)
private val predictor = MotionEventPredictor.newInstance(this)
private val brush = Brush.createWithColorIntArgb(
family = StockBrushes.pressurePen(),
colorIntArgb = Color.BLACK,
size = 5f,
epsilon = 0.1f,
)
init {
addView(layer)
addView(inProgress)
inProgress.addFinishedStrokesListener(this)
}
override fun onStrokesFinished(strokes: Map<InProgressStrokeId, Stroke>) {
// The documented handoff: in one UI-thread loop, start drawing the strokes here and stop drawing
// them there. Done in two loops, a frame shows a gap or a double draw.
layer.finished.addAll(strokes.values)
layer.invalidate()
inProgress.removeFinishedStrokes(strokes.keys)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
predictor.record(event)
val pointerId = event.getPointerId(0)
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
requestUnbufferedDispatch(event) // the library's documentation recommends this
inProgress.startStroke(event, pointerId, brush)
}
MotionEvent.ACTION_MOVE -> inProgress.addToStroke(event, pointerId, predictor.predict())
MotionEvent.ACTION_UP -> inProgress.finishStroke(event, pointerId)
MotionEvent.ACTION_CANCEL -> inProgress.cancelStroke(event, pointerId)
}
return true
}
}
startStroke takes the first event and a pointer ID, not an index (guide 5), and addToStroke takes the predicted event as an optional third argument. When the
last stroke finishes, the view calls onStrokesFinished and keeps drawing the strokes until you remove them. The library’s documentation asks for the handoff in the snippet to happen in one UI-thread loop,
and why a gap or a double draw appears when it doesn’t is the subject of the next guide. The snippet handles one pointer and doesn’t save the strokes anywhere; it has been compiled, not run.
Checkpoint
You should be able to say:
- A stroke on screen is a shape: a centreline, a width at each point, and triangles between the two outlines.
- A spline through the points passes through the noise; only an average removes it, at the price of rounding corners.
- Ink averages the raw path over a 20 ms window centred on each point and adds points where samples are far apart, and the newest half window is provisional.
- Width comes from behaviors with ranges and response times, and a panel’s constant pressure carries no information.
- A turn tighter than the line is wide folds a plain offset strip, and noise makes tiny reversals that fold it too.
- Ramer-Douglas-Peucker drops outline vertices within
epsilonof the line, and in Ink oneepsilonalso bounds the arc chord height. - A
Meshhas 16-bit indices, aPartitionedMeshholds several (library-internal in 1.0.0), and Ink draws a mesh on Android 14 and later and a path before that.
Why it helps
| Symptom | What is happening | What to do |
|---|---|---|
| A fast stroke shows corners at every sample | A polyline joins distant points with straight chords | Interpolate: a spline, or an input model that adds points between samples |
| A spline made the line wobblier on a noisy pen | It passes through every noisy point | Average first (a window or a Kalman filter), then interpolate |
| The line is smooth but its sharp corners are rounded | The 20 ms window averages across the corner | Nothing in an app: the stock brushes’ window is fixed and the model API is restricted in 1.0.0. A higher report rate narrows it; for sharp-cornered drawing, do your own modeling and draw from your own points |
| Width flutters or never changes on a touch panel | Pressure is a constant 0.5, and speed from noisy points jumps | Take width from speed after smoothing, or a fixed width; check the tool type |
| Backwards triangles at a turn, or notches in a thick line | The outline folds where the turn is tighter than the width | Round joins on the outside, and a rule for the inside, as Ink’s extruder has |
| A stroke has many more vertices than its shape needs | Every sample, or eight per sample from a spline, becomes two vertices | Simplify the outline with Ramer-Douglas-Peucker; set epsilon from the zoom |
| A very long stroke needs more than one mesh | A Mesh has 16-bit indices |
Nothing: Ink splits it into a PartitionedMesh and its renderer draws each part |
The map
| Topic | Code | Where |
|---|---|---|
| Ink’s source | the C++ core | github.com/google/ink |
| The input model | SlidingWindowInputModeler |
sliding_window_input_modeler.cc |
| The defaults | BrushFamily::SlidingWindowModel |
brush_family.h |
| Extruding a stroke | BrushTipExtruder |
brush_tip_extruder.h |
| The triangulation | Geometry, with the design notes |
line_mesh_generation.md |
| Simplification | SimplifyPolyline |
simplify.cc |
| The mesh container | PartitionedMesh |
partitioned_mesh.h |
| Kotlin API | InProgressStroke, Stroke, Brush |
reference, releases |
| Drawing | CanvasStrokeRenderer, Canvas.drawMesh |
Canvas.drawMesh |
Edge cases
- A stroke of one point. Three samples at one place leave one modeled point (the library’s test). What is drawn for a tap depends on the brush tip, and this guide hasn’t followed it through.
- Dashes and dots. The extruder puts a break in the mesh where a tip’s width and height both fall below
epsilon, so a brush can make gaps. - Zoom.
epsilonand the brush size are in stroke units. A stroke drawn at one zoom and shown at another needs its transforms set so they match, asstartStrokedocuments. - The window and the report rate. The window is 20 ms in every stock brush; what that means depends on the device, about five samples at 240 Hz and about one at 60 Hz.
- Provisional points. Anything built from the newest half window of the input will change. Don’t cache the mesh of the last few points as final.
- The mesh is not yours to read. In 1.0.0 an app can’t read a stroke’s triangles; it gets outlines, bounds and coverage. Anything that needs the triangles (a custom renderer, an export) is outside the supported API.
- Version differences. This is Ink 1.0.0. The core’s
mainhas changed the input models and keeps changing them; read the version you ship.
Cross questions
Why not draw a stroke as a Path with a stroke style?
You can, when the width is constant. A Paint has one stroke width for the whole path, so a width that follows pressure or speed needs a filled outline or a mesh. Ink falls back to a filled path of the outline before Android 14, and uses a mesh from Android 14.
A spline passes through every point. So why isn't it the most accurate centreline?
Because the points are noisy. A curve through noisy points is a smooth curve through the noise. In the lab's tables (means of 8 sequences) at 2 px of noise and 240 Hz it is 1.79 px from the true path against 1.67 px for the polyline, and it has eight times the points. On clean data at 60 Hz it halves the error (0.38 against 0.74 px).
Ink's window is 20 ms. Is that the same smoothing on a 60 Hz and a 240 Hz pen?
It is the same span of time, but not the same number of samples: about five at 240 Hz, about one at 60 Hz. At 60 Hz the average has almost nothing to average, so it barely removes noise and still rounds corners. In the lab's tables it is 1.37 px from the true path against 1.09 px for the raw polyline at 60 Hz and 1 px of noise.
Why does the sliding window cut corners, and does Ink fix it?
An average over 20 ms includes points from before and after the corner, so it lands inside the bend. Ink's test with an L-shaped path shows modeled points like (59.5, 0.5) and (68, 2) where the raw path turns at (100, 0). The library doesn't undo that, and an app can't narrow the window in 1.0.0, because the stock brushes fix it at 20 ms. A higher report rate makes the rounding smaller, because the same 20 ms then covers more samples that are closer to the corner.
Why does the outline fold at a sharp turn?
Each side moves half the width away from the path. On the inside of a turn tighter than the line is wide, the offset points cross each other, so the triangle between two steps has its corners in the wrong order. A plain offset can't avoid that. Ink detects the bad winding as it builds the mesh and rewrites some of the triangles it already added.
What does epsilon actually do?
It is the smallest distance for which two points count as different. Ink uses it as the minimum spacing of modeled points, the threshold for simplifying each outline, the maximum chord height of the arcs at turns, and the size below which a tip makes no mark. Lower is smoother and costs more vertices. The documentation suggests 0.1 physical pixels at the default zoom.
Why does a PartitionedMesh exist at all?
A Mesh has 16-bit triangle indices, which limits how many vertices one mesh can address. A long, detailed stroke needs more, so Ink splits it into several meshes and holds them together, and the renderer draws each in turn. It also holds one group of meshes per brush coat, plus outlines and a spatial index. An app sees the group count, the outlines and the bounds, not the meshes.
The pen reports pressure, but the width doesn't change in my drawing. Why?
Check the stock pen's term: below a pressure of 0.8 it does nothing, and it only applies to a stylus. A light stroke stays at the base size. Check also the tool type: a finger or a panel reports a constant, which carries no information.
Revision: key points
- A stroke is a centreline, a width at each point, and triangles between two outlines.
- A Catmull-Rom segment is the cubic Bézier with control points
P1 + (P2 - P0) / 6andP2 - (P3 - P1) / 6; it passes through noise, so average first. - Ink’s default input model averages the raw path over a 20 ms window centred on each point, and upsamples to 180 Hz; the newest half window is unstable.
- Width comes from behaviors: a source, a range, a clamp and a response time; the stock pen’s pressure term starts at 0.8 and applies to a stylus.
- A strip has 2n vertices and 2(n - 1) triangles, and folds where the turn is tighter than the line is wide.
- Round joins add outside arcs whose chord height is at most
epsilon: each step is at most 2 acos(1 - epsilon / r). - Ramer-Douglas-Peucker keeps the point farthest from the chord if it is more than
epsilonaway, and recurses; Ink applies it to each outline. - A
Meshhas 16-bit indices; aPartitionedMeshholds several, per brush coat; Ink draws meshes on Android 14 and later and paths before that.
Cheat sheet
Each concept in a few words.
| Concept | In a few words |
|---|---|
| Centreline | The cleaned path a stroke follows. |
| Catmull-Rom | A curve through every point; each piece is a cubic Bézier. |
| Sliding window | Averages 20 ms around each point; it also cuts corners. |
| Upsampling | Adds points between sparse samples (Ink: 180 Hz). |
| Width source | Pressure, speed or a constant; a panel’s pressure carries nothing. |
| Offset outlines | Each point moved left and right by half the width. |
| Triangle strip | 2n vertices and 2(n - 1) triangles between the outlines. |
| Fold | Backwards triangles where a turn is tighter than the line is wide. |
epsilon |
The smallest distance that counts as different; sets mesh detail. |
| Ramer-Douglas-Peucker | Drops outline points within epsilon of the line. |
PartitionedMesh |
Ink’s meshes grouped per brush coat; 16-bit indices per mesh. |
Read next
- References: Jetpack Ink releases and the
InProgressStrokereference - The papers: Yuksel, Schaefer and Keyser, “Parameterization and applications of Catmull-Rom curves” (2011) and Ramer, “An iterative procedure for the polygonal approximation of plane curves” (1972)
- Wikipedia, for a gentler start: centripetal Catmull-Rom spline and Ramer-Douglas-Peucker
- The source, in The map above, especially
line_mesh_generation.md
Search terms that find more: Catmull-Rom spline Bézier conversion, centripetal Catmull-Rom, Ramer Douglas Peucker algorithm, stroke tessellation, polyline offset triangle strip, androidx.ink InProgressStrokesView, Canvas.drawMesh.
The fine print
The Ink excerpts are from the jetpack-1.0.0 tag of google/ink (3 November 2025) and from the Kotlin sources of androidx.ink 1.0.0; the snippets
compile against those artifacts. The lab is a TypeScript model: its sliding window and simplification are ports of Ink’s, and match the library’s own test cases
(the L-shaped path and the 14-point line) to the test’s tolerance; its outline offsetting and stitching follow the idea in the extruder’s notes and not its tip-shape sweep, and it does not
retriangulate a fold. It was not run against the released library. Its stroke is one synthetic path, and every figure in the tables is a mean of 8 noise sequences from the model, not a
measurement of a device. The stock pen’s other terms (speed, direction, acceleration) are described from the source and not modeled. The BrushBehavior and renderer excerpts are library source, which an app
can’t compile (the behavior API is restricted in 1.0.0); every other snippet compiles against the 1.0.0 artifacts and passes lint at minSdk 26 (one performClick accessibility warning on the touch view). The stable and unstable behavior is
described for real inputs only; how predicted inputs are modeled is from the modeler’s documentation and not tested here, and the lab scores the finished stroke, not its provisional tail. The Kotlin
snippets were compiled and linted, not run on a device. The lab was checked in one desktop browser, in both themes and at a narrow container width, and not 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.