What you’ll study
- Three erasers: one that clears pixels, one that removes whole strokes, one that cuts strokes in two, and what each throws away.
- Hit testing a moving eraser: why testing the pen’s samples loses strokes, and what to test instead.
- Testing one stroke: its bounding box, then its triangles, and what Jetpack Ink’s
intersectsandcomputeCoveragedo. - Finding the strokes to test in a document of thousands: a grid, an R-tree, and why an index that never changes fits a stroke but not a page.
- Cutting a stroke: the two ways that work in Ink 1.0.0, and the experimental one in 1.1.
- Tools, palms, undo, and what to show while erasing.
How it connects
Guide 7 built the triangles of a stroke and said Ink holds them in a PartitionedMesh with a spatial index; this guide is what that index is for. Guide 2 made
a pixel eraser with BlendMode.CLEAR and said it can’t undo one stroke. Guide 8 ended with the strokes in your own view, because a front layer holds pixels and can’t erase anything. Guide 5 covered the
eraser end of a pen and the cancel a palm can cause.
Read it at your level
| Level | Read | You should be able to |
|---|---|---|
| Student | The basics, the lab | Say the difference between erasing pixels and erasing strokes |
| Fresher | + The high level, the eraser as a path | Say why a fast pen can jump over a stroke, and the fix |
| Junior | + One stroke, many strokes | Explain a bounding-box test, a grid and an R-tree, and what each costs |
| Mid | + Cutting, in an app | Cut a stroke at an eraser, and say what a new stroke from part of the inputs loses |
| Senior | + Edge cases, cross questions | Choose an index for a page that changes on every erase, and say what to measure |
The basics
An eraser is a pen that takes ink away. What it takes away depends on what the ink is.
- Pixels. If the page is a picture, an eraser paints transparent over it (guide 2). It is cheap and simple, and the strokes are gone as objects, so you can’t undo one stroke or move it.
- Whole strokes. If the page is a list of strokes, an eraser finds the strokes it touches and removes them from the list. Nothing is painted. The page is drawn again without them.
- Parts of strokes. The eraser cuts: the stroke becomes the pieces the eraser did not reach.
The last two need a question answered quickly, many times a second: which strokes does the eraser touch? That is a hit test. A pen reports 60 to 240 times a second, a page can have thousands of strokes, and each stroke is a shape of many triangles (guide 7). Answering it by testing everything works on a small page and stops working on a large one, so most of this guide is about answering it with less.
Try it: the eraser lab
A page of strokes, and an eraser. Drag across it, or press Sweep a fast pass, which runs the same pen path every time. The stat cards below the page count the work done, not how long it took: how many strokes were asked about the eraser, how many bounding boxes were compared with it, how many exact triangle tests ran. A dashed line is a stroke that has been removed.
Things to try. Each starts from the lab’s defaults (Eraser: Remove strokes; It tests: Swept segments; Strokes found by: Each stroke; Eraser radius 8 px; Sweep samples every 60 px; Strokes 200; Stroke samples 4–7 px) and names every setting it changes. Every number comes from pressing Sweep a fast pass, not from dragging.
- A fast pen skips strokes. Press Sweep: 63 of the 200 strokes are removed. Set It tests to Pen samples, and press Sweep again: 40. At Sweep samples every 90 px it is 24, and at 30 px it is 58; at 6 px it is 63 again. Testing the segments between samples always finds 63. The gap between samples is the pen’s speed divided by its report rate: 60 px is 3,600 px/s at a 60 Hz report rate, or 14,400 px/s at 240 Hz, and the lab’s 6 px is 360 px/s at 60 Hz.
- An index replaces the triangle scan. Set Sweep samples every to 6 px. With Strokes found by Every triangle, 953,595 triangle tests run. With Each stroke, 87 do, plus 20,057 bounding boxes compared, because all 16,655 strokes are still asked at every step. Grid asks 2,169 strokes, compares 5,571 boxes and looks up 266 cells. R-tree asks 269 strokes and compares 8,278 boxes. All four remove the same 63 strokes.
- An R-tree that never changes is rebuilt. With Sweep samples every at 6 px and Strokes found by R-tree, the builds card shows 47 (7,998 boxes sorted): the first is the initial build, and after that each time the eraser removes a stroke the next query has to build the tree again. Grid shows 0.
- More strokes, more asking. With Sweep samples every at 6 px, set Strokes to 800. Each stroke compares 80,235 boxes, Grid 20,236 (and 266 cell lookups) and R-tree 21,866, with 84 builds (57,824 boxes sorted). At 100 strokes they are 10,062, 2,894 and 5,270, with 28 builds.
- Cutting. Set Sweep samples every to 6 px, and Eraser to Cut by segments, then to Cut at the edge. Dropping whole segments removes 2,321 px of ink, and cutting at the edge 1,935 px, which is what the eraser covered. The sweep’s spacing changes neither number. The strokes’ own spacing does: set Stroke samples to 30 px and the same two cuts remove 3,229 px and 1,709 px.
The lab is a TypeScript model. Its R-tree is a port of Ink’s, and it matches the library’s own test cases; the coverage function matches Ink’s tests; the document-level indexes, the swept query and the two cuts are this guide’s own. The partial erasers always test the swept segment.
The high level
| Step | What it does | What it costs |
|---|---|---|
| Shape the eraser | Turn the pen’s last two samples into a rectangle: the segment, padded by the eraser radius | A rectangle’s corners reach farther than a round eraser |
| Find candidates | Use an index over strokes’ bounding boxes: a grid or an R-tree | An R-tree that never changes must be rebuilt when a stroke is removed |
| Test one stroke | Ask the stroke’s own triangle index whether any triangle meets the rectangle | A few triangle tests per stroke, after a quick bounds rejection |
| Decide | Remove the stroke, or cut it into the pieces that survive | Cutting rebuilds each piece’s mesh |
| Record | One undo step per gesture: what was removed and what replaced it | Pieces need new strokes, and the order has to be kept |
The low level
Source excerpts are from the C++ core of google/ink at the jetpack-1.0.0 tag and the Kotlin sources of androidx.ink 1.0.0, trimmed with …, and from the Kotlin sources of 1.1.0-alpha11 where the text says so. Links are in The map.
1. Three erasers
The pixel eraser is guide 2’s BlendMode.CLEAR on the ink’s own layer. It needs no geometry and keeps no record of strokes; what it can’t do is undo one stroke, move one, or keep the page as vectors. A front-buffered layer (guide 8) can’t be erased either: it holds pixels, so strokes that can be erased live in your data and are drawn by the dry path.
The whole-stroke eraser is the one Google’s own geometry page shows: build a shape from the eraser’s last two points, remove every stroke whose shape intersects it. The partial eraser needs the same test and then cuts. Both need the same first step.
2. The eraser is a path, not a point
The pen reports samples. The eraser between two samples was somewhere, and a fast stroke leaves samples far apart. Testing only the sample positions treats the pen as if it jumped: a stroke lying between two samples is never touched.
The fix is to test the segment between samples, with the eraser’s radius around it. The same page of Google’s documentation does this: it builds a parallelogram from the segment and a padding with fromSegmentAndPadding. In the Ink source that constructor is short:
// library source: ImmutableParallelogram.fromSegmentAndPadding (androidx.ink 1.0.0), trimmed
normalizeAndRun(
width = segment.computeLength() + 2 * padding,
height = 2 * padding,
rotationDegrees = Angle.radiansToDegrees(atan2(segment.start.y - segment.end.y, segment.start.x - segment.end.x)),
) { … }
It is a rectangle aligned with the segment, as long as the segment plus the padding at each end and twice the padding across. A rectangle is not a capsule: each corner is the padding times the square root of two from the segment’s end, so it reaches about 0.41 times the padding beyond a round eraser. For an 8 px eraser that is about 3 px. The lab and Ink’s example both use it.
In the lab, a 60 px gap between samples with an 8 px radius makes the test of samples lose 23 of 63 strokes (40 found), and a 6 px gap loses none. In general, testing samples is enough only when they are closer together than the eraser is wide. The name for the problem in games is tunnelling; the fix is swept or continuous collision testing.
3. One stroke: bounds, then triangles
A Stroke in Ink holds a PartitionedMesh, the triangles of guide 7. The public geometry API tests that mesh against simple shapes. For the whole-stroke eraser it is a single call:
stroke.shape.intersects(sweep, strokeToScreen) is Intersection.intersects for a PartitionedMesh against a Parallelogram. The transform maps from the mesh’s coordinates to the shape’s. The documentation says why it is passed in: applying a transform to a mesh is expensive, so Ink applies the inverse to the small query shape instead.
How can that be quick? Each PartitionedMesh has a spatial index over its triangles, built the first time a query needs it (or by initializeSpatialIndex()). It is a StaticRTree, in static_rtree.h:
- An R-tree is a tree of bounding rectangles: each node holds the rectangle around everything below it, so a query skips whole branches whose rectangle it doesn’t touch. Guttman described it in 1984.
- Static means it is built once from a fixed list and never changed, “best suited for uses in which you compute the set of objects once”, and its header names stroke meshes as the example.
- It is bulk loaded with the Sort-Tile-Recursive method: sort by x, cut into vertical slices, sort each slice by y, pack tiles of 16 (the default branching factor) into parents, and repeat up the levels. The branch nodes sit in one array and refer to each other by index.
A query visits the elements whose bounds meet the query’s bounds, then tests the triangle exactly. This is the core of PartitionedMesh’s queries:
// partitioned_mesh.cc, VisitIntersectedTrianglesHelper, trimmed; [note] comments are mine
auto visitor_wrapper = [transformed_query, visitor, &meshes](TriangleIndexPair index) {
if (!geometry_internal::IntersectsInternal(
transformed_query, meshes[index.mesh_index].GetTriangle(index.triangle_index))) {
return true; // [note] bounds met, triangle did not: keep looking
}
return visitor(index) == PartitionedMesh::FlowControl::kContinue;
};
rtree.VisitIntersectedElements(*Envelope(transformed_query).AsRect(), visitor_wrapper);
intersects stops at the first triangle (in intersects.cc the visitor sets a flag and returns kBreak), after applying the inverse of the transform to the query shape. Coverage keeps going: it adds up the absolute areas of the triangles that intersect, and divides by the total.
// partitioned_mesh.cc, ComputeCoverage and CoverageIsGreaterThanHelper, trimmed
covered_area += std::abs(target.Meshes()[index.mesh_index].GetTriangle(index.triangle_index).SignedArea());
…
return covered_area > area_threshold ? PartitionedMesh::FlowControl::kBreak : PartitionedMesh::FlowControl::kContinue;
Two things follow from that code, and the library’s own tests show them (the lab’s model passes the same cases): the coverage is the share of the whole triangles that touch the query, not the part of them inside it, so a pixel-sized nick on a large triangle counts as that triangle’s whole area; and so a threshold above zero depends on how big the touched triangle is. In the library’s test shape of four triangles with areas 10%, 20%, 30% and 40%, a tiny square on the first gives 0.1 and on the last 0.4. The documentation calls the measure approximate, and says computeCoverageIsGreaterThan(…, t) equals computeCoverage(…) > t but may be faster. For an eraser, intersects, or a threshold of zero, is the honest test: any touch.
4. Many strokes: finding the candidates
Asking every stroke at every sample is fast per stroke and slow in total. Each stroke’s own index rejects a far-away eraser at its root rectangle, but you still ask, and in the lab with 800 strokes and a 6 px pass, strokes are asked about the eraser 68,481 times. Ink 1.0.0 indexes one stroke’s triangles. I found no index over many strokes in its geometry or strokes modules, so finding which strokes to ask is the app’s job. Two ways, and the lab’s Grid and R-tree are this guide’s own code:
- A grid. Cut the page into cells (the lab uses 64 px). Each stroke is listed in the cells its bounding box covers. The eraser asks only the strokes in the cells it overlaps. Adding or removing a stroke changes a few cells.
- An R-tree over the strokes’ bounding boxes, the same structure as above. It asks far fewer strokes than the grid in the lab (269 against 2,169 at 200 strokes and a 6 px gap), but it compares more boxes (8,278 against 5,571, plus the grid’s 266 cell lookups), and it is static.
That matters because an eraser changes the page on every hit. A static tree can’t remove a stroke: the lab builds it 47 times in a pass, the first time at the start and then once after each erase, sorting the boxes each time (7,998 in all). On this page the grid compares fewer boxes and never builds, so it does less in the lab’s counts, while the R-tree asks fewer strokes. The counts are of different operations, so they don’t add up to a cost. Options are a grid, which absorbs removal; rebuilding lazily and once per gesture; or a tree that supports removal, which Ink’s doesn’t. Which is best depends on the page, and the lab only counts; measure on yours.
The R-tree in the lab is a port of Ink’s StaticRTree. It reproduces the library’s tree layouts for 5, 12 and 16 points (branching factor 3), the node counts for 10, 100, 1000 and 10,000 elements at the default of 16 (1, 8, 68 and 669), and its rectangle and circle queries. One difference: Ink sorts with std::sort, which is not stable, and JavaScript’s sort is, so inputs with equal coordinates can come out in a different order.
5. Cutting a stroke
The official page says how: check the stroke’s StrokeInputBatch segment by segment against the eraser, and build new StrokeInputBatch and Stroke objects from the segments that weren’t touched. This is the lab’s Cut by segments. Its limits:
- The cut is at a sample, not at the eraser’s edge. Each segment that touches is dropped whole, so the gap is up to a segment longer than the eraser on each side. In the lab, with strokes sampled 4 to 7 px apart, it removes 20% more ink than the eraser covered (2,321 px against 1,935 px); with strokes sampled every 30 px, 89% more (3,229 against 1,709). The spacing that matters is the stroke’s own, not the pen path the eraser follows.
- A new stroke is a new pipeline.
Stroke(brush, inputs)runs the whole input model and extrusion again on the surviving inputs (guide 7). The sliding window clamps at the new ends (guide 7), and anything in the brush that depends on the start of the stroke starts again at the piece’s first input, so expect a piece to differ from the old mesh near its ends. - Inputs are validated.
MutableStrokeInputBatch.addthrows if an input repeats one, goes back in time, or differs in tool type or in which of pressure, tilt and orientation it carries. Copying inputs from an existing batch, in order, keeps those rules. A piece starts at a later elapsed time than zero, which the rules don’t forbid, but I haven’t run it.
The lab’s Cut at the edge does what an exact cut would: it finds where the centreline enters and leaves the eraser, which is one interval per segment because the distance to the eraser is convex along a straight segment, and puts new end points there. That is this guide’s geometry, a model of the idea. It is not Ink’s behaviour.
What Ink adds, in an alpha. Ink 1.1.0-alpha11 has an experimental Stroke.subtract(maskShape, maskToWorldTransform, strokeToWorldTransform). Per its documentation it removes a mask shape from a stroke’s geometry: the result keeps the original inputs and brush and gets a new shape, and changing the brush size afterwards undoes the cut. It can be expensive and is meant for a worker thread. A stroke can end up in disconnected parts, and split(strokeToWorldTransform, tolerance) separates them into
separate strokes (it suggests the eraser’s size for the tolerance). Both are behind @ExperimentalInkEraserApi; the alpha 10 notes mention anti-aliasing the cut edges, and alpha 11 adds serialization of the shape, “to save partially erased strokes”. None of it is in 1.0.0, so for a stable build the cut is the inputs route.
6. Tools, palms, undo, and the screen
Which tool is erasing? The eraser end of a pen reports TOOL_TYPE_ERASER; the barrel button is in the button state (guide 5). Beyond that it is a design choice: a tool picker, a button, a pen flip.
A palm as an eraser is a design choice too, and this guide found no platform source for it. A touch reports a contact size (getTouchMajor, getTouchMinor, guide 5), and a large contact can be treated as an erase with a rectangle that size. Two cautions: the system’s palm rejection may cancel the pointer first, on devices that turn it on (guide 4), and a device that doesn’t report contact size (guide 5 lists the axes) gives you nothing to threshold on.
Undo. One erase gesture is one undo step: record the strokes removed, with their positions in the z-order, and the strokes added. A cut stroke is a removal and several additions, and the pieces should take the old stroke’s place in the order, or a stroke can jump above its neighbours.
What to show. Removing a stroke as soon as the eraser touches it feels direct. Marking it and removing on lift lets the user abort, and the cancel from a palm (guide 5) can abort the gesture. Either way the dry layer is drawn again without the strokes, and how much of it to redraw is guide 11.
7. In an app
The whole-stroke eraser follows Google’s page: it remembers the previous sample, builds the swept rectangle, and asks each stroke. strokeToScreen is the transform from the stroke’s coordinates to the space the pen’s samples are in.
class WholeStrokeEraser(private val radius: Float) {
private var previous: ImmutableVec? = null
/** The strokes the eraser touched on the way from the previous sample to (x, y). */
fun move(x: Float, y: Float, strokes: List<Stroke>, strokeToScreen: AffineTransform): List<Stroke> {
val here = ImmutableVec(x, y)
val sweep = ImmutableParallelogram.fromSegmentAndPadding(ImmutableSegment(previous ?: here, here), radius)
previous = here
return strokes.filter { it.shape.intersects(sweep, strokeToScreen) }
}
fun lift() {
previous = null
}
}
For a page, put an index in front of it. A grid of bounding boxes is enough for most pages. Strokes here are in document coordinates, so a stroke’s box is shape.computeBoundingBox():
class StrokeGrid(private val cell: Float = 64f) {
private val cells = HashMap<Long, MutableSet<Stroke>>()
private val cellsOf = HashMap<Stroke, List<Long>>()
private fun key(cx: Int, cy: Int): Long = (cx.toLong() shl 32) xor (cy.toLong() and 0xffffffffL)
private fun keysFor(box: Box): List<Long> {
val keys = ArrayList<Long>()
for (cx in floor(box.xMin / cell).toInt()..floor(box.xMax / cell).toInt()) {
for (cy in floor(box.yMin / cell).toInt()..floor(box.yMax / cell).toInt()) keys.add(key(cx, cy))
}
return keys
}
fun add(stroke: Stroke) {
val box = stroke.shape.computeBoundingBox() ?: return
val keys = keysFor(box)
cellsOf[stroke] = keys
for (k in keys) cells.getOrPut(k) { HashSet() }.add(stroke)
}
fun remove(stroke: Stroke) {
for (k in cellsOf.remove(stroke) ?: return) cells[k]?.remove(stroke)
}
/** The strokes whose bounding box shares a cell with `region`. They still need an exact test. */
fun candidates(region: Box): Set<Stroke> {
val out = HashSet<Stroke>()
for (k in keysFor(region)) cells[k]?.let { out.addAll(it) }
return out
}
}
And the cut by segments, from the official suggestion. The padding has to include half the stroke’s width, because the segments are centrelines:
fun cutBySegments(stroke: Stroke, sweep: Parallelogram): List<Stroke> {
// assumes the stroke's inputs and the sweep are in the same coordinate space
val inputs = stroke.inputs
if (inputs.size < 2) return listOf(stroke)
val pieces = ArrayList<Stroke>()
var run = MutableStrokeInputBatch()
val a = StrokeInput()
val b = StrokeInput()
fun flush() {
if (run.size >= 2) pieces.add(Stroke(stroke.brush, run))
run = MutableStrokeInputBatch()
}
for (i in 0 until inputs.size - 1) {
inputs.populate(i, a)
inputs.populate(i + 1, b)
val segment = ImmutableSegment(ImmutableVec(a.x, a.y), ImmutableVec(b.x, b.y))
if (segment.intersects(sweep)) {
flush() // the eraser reached this segment: end the piece before it
} else {
if (run.isEmpty()) run.add(a)
run.add(b)
}
}
flush()
return pieces
}
Calling it needs the eraser’s rectangle padded by the eraser’s radius plus half the brush size: ImmutableParallelogram.fromSegmentAndPadding(segment, radius + stroke.brush.size / 2f). The strokes the erase replaces, with the pieces that take their places, go into one undo command; a stroke removed whole has no pieces:
class Replacement(val index: Int, val original: Stroke, val pieces: List<Stroke>)
class EraseCommand(private val replacements: List<Replacement>) {
/** `page` is the page as it was when the erase was recorded: each piece takes the place of its stroke. */
fun apply(page: MutableList<Stroke>) {
val byIndex = replacements.associateBy { it.index }
val result = ArrayList<Stroke>(page.size)
page.forEachIndexed { i, stroke -> result.addAll(byIndex[i]?.pieces ?: listOf(stroke)) }
page.clear()
page.addAll(result)
}
fun revert(page: MutableList<Stroke>) {
page.removeAll(replacements.flatMap { it.pieces }.toSet())
// ascending order puts each original back at its old index
for (r in replacements.sortedBy { it.index }) page.add(minOf(r.index, page.size), r.original)
}
}
A palm as an eraser, if you choose that, is a small check on the contact size, with a threshold you pick for your devices:
fun palmEraserRadius(e: MotionEvent, i: Int, thresholdPx: Float): Float? {
if (e.getToolType(i) != MotionEvent.TOOL_TYPE_FINGER) return null
val size = maxOf(e.getTouchMajor(i), e.getTouchMinor(i))
return if (size > thresholdPx) size / 2f else null
}
Checkpoint
You should be able to say:
- A pixel eraser clears paint; a stroke eraser removes objects; a partial eraser cuts them. Only the last two need a hit test.
- Testing the pen’s samples loses strokes a fast pen crossed; test the segment between samples, with the eraser’s radius.
Parallelogram.fromSegmentAndPaddingis a rectangle of the segment’s length plus the padding at both ends, and twice the padding across.- Ink indexes one stroke’s triangles with a static R-tree, and a query is a bounds test and then an exact triangle test.
- Coverage adds up the whole areas of the touched triangles, so a threshold above zero depends on triangle size; for an eraser use
intersects. - Ink 1.0.0 has no index over a page; a grid absorbs removals and a static R-tree must be rebuilt.
- Cutting by input segments removes up to a sample on each side too much; Ink 1.1 alphas have an experimental
subtractthat cuts the geometry. - An erase is one undo step: what was removed, with its position, and what replaced it.
Why it helps
| Symptom | What is happening | What to do |
|---|---|---|
| A quick swipe leaves strokes standing | The test looked at the samples, not between them | Test the segment, padded by the eraser’s radius |
| The eraser lags on a big page | Every stroke is asked at every sample | Put a grid or an R-tree of bounding boxes in front |
| A light touch on a big stroke removes it | You used a coverage threshold above zero | Use intersects, or a threshold of zero, for an eraser |
| A cut leaves a gap wider than the eraser | The cut drops whole segments between samples | Cut at the eraser’s edge, or use the experimental Stroke.subtract |
| A piece looks different from the stroke it came from | Stroke(brush, inputs) ran the pipeline again on a subset |
Expect small changes at the ends; keep the original for undo |
IllegalArgumentException when making a piece |
An input repeated, went back in time, or had a different tool type or fields | Copy inputs from the original batch in order, and catch the exception |
| Undo puts a stroke above its neighbours | The order was not recorded | Store each removed stroke with its index |
| A scaled or panned page erases the wrong strokes | The transform passed to intersects was the wrong way round |
It maps from the stroke’s coordinates to the eraser’s |
| An R-tree is slower than a grid | It is rebuilt after every removal | Rebuild once per gesture, or use a grid |
The map
| Topic | Code | Where |
|---|---|---|
| Google’s eraser example | Geometry APIs | Geometry APIs |
| Intersection functions | Intersection, PartitionedMesh.intersects |
Intersection.kt |
| Coverage and the spatial index | PartitionedMesh::Coverage, Data::SpatialIndex |
partitioned_mesh.cc |
| The R-tree | StaticRTree |
static_rtree.h, tests |
| Coverage tests | MakeRisingSawtoothShape |
partitioned_mesh_test.cc |
| The swept rectangle | ImmutableParallelogram.fromSegmentAndPadding |
source |
| Building strokes from inputs | Stroke, MutableStrokeInputBatch |
Stroke.kt |
| The experimental partial eraser | Stroke.subtract, Stroke.split |
Ink releases |
| Tool types and palms | TOOL_TYPE_ERASER, getTouchMajor |
guide 5 |
| The papers | R-trees; Sort-Tile-Recursive | Guttman 1984, Leutenegger, Lopez and Edgington 1997 |
Edge cases
- A tap. One sample gives a zero-length segment, so the eraser is a square of side twice the radius. The lab and
fromSegmentAndPaddingboth do that. - A stroke the rectangle’s corner touches. The rectangle is larger than a round eraser at its corners, so a stroke can be touched by the corner and not by the circle. The lab’s cut notices that nothing was under the eraser and leaves such a stroke alone.
- Looping strokes. Triangles that overlap each other count separately in coverage, as Ink’s documentation says.
- Transforms. Zoom and pan change the transform for every query. Ink applies the inverse to the query shape, so the cost is small, but the direction matters: the transform maps from the stroke to the query.
- Hover. An eraser cursor over a stroke before the pen touches the glass is a hover (guide 5), not a touch; decide whether it should preview.
- Many pieces. Cutting makes more strokes. A page that is heavily cut has more strokes, and each piece has its own mesh and index.
- Version differences. This is Ink 1.0.0.
Stroke.subtractandsplitexist only in the 1.1 alphas and are experimental.
Cross questions
Why not test the pen's position against each stroke?
Because the pen is sampled. At a 60 Hz report rate a pen moving 2,000 px/s travels 33 px between samples (guide 8 used 1,000 to 2,000 px/s), and an 8 px eraser is 16 px wide. In the lab, samples 60 px apart (3,600 px/s at 60 Hz) find 40 of 63 strokes, and 30 px apart find 58. A faster report rate shrinks the gap; testing the segment between samples closes it.
Why does Ink build a parallelogram and not a circle swept along the segment?
Its geometry API tests meshes against points, segments, triangles, boxes, parallelograms and other meshes, and a parallelogram padded by the radius is the one that fits a swept eraser. The cost is its corners, which stick out of a round eraser. The documentation's own eraser example uses it.
Is computeCoverage the right test for an eraser?
Not for "did it touch?". It adds up the whole areas of the triangles that touch the query, divided by the total, so a tiny nick on a big triangle counts as that triangle. intersects, or computeCoverageIsGreaterThan(…, 0f), is the test for any touch. A threshold above zero is for a rule like "erase when more than a tenth is covered", knowing it depends on triangle size.
Why is Ink's R-tree "static", and does that matter for an eraser?
It is built once from a fixed list of triangles, which is exactly a finished stroke: strokes don't change. A page does change, on every erase, and a static tree can only be rebuilt. For a per-stroke index that is fine. For an index over the page, use a grid, or rebuild once per gesture.
Does a grid beat an R-tree?
Not always. In the lab's counts the R-tree asks far fewer strokes (269 against 2,169 at 200 strokes) but compares more boxes (8,278 against 5,571) and is built 47 times in a pass, after every removal. The grid asks more strokes and never builds. Which wins depends on how many strokes the eraser removes and what a build costs on your page; the counts are of different operations, so measure.
Why does cutting by segments take out more than the eraser touched?
Because it drops whole segments between inputs, and the cut can only fall on an input. The ink removed is the eraser's width plus up to a segment on each side. With fine sampling it is close; with coarse sampling it is not. The lab shows 2,321 px removed against 1,935 px covered with strokes sampled 4 to 7 px apart, and 3,229 against 1,709 at 30 px.
Why does a piece of a stroke not look exactly like the original?
Because Stroke(brush, inputs) builds the stroke again from the inputs you give it, and the input model and the brush behaviors begin at the new first input (guide 7). The sliding window clamps at the ends, and time-based terms start over. The experimental subtract avoids that by cutting the existing shape and keeping the inputs.
Can a palm be the eraser?
It can be a design choice: a touch with a large contact size, treated as an erase. Ink has no such thing, and nothing here was found in a platform source. The system's palm rejection may cancel the pointer first on devices that enable it (guide 4), and a device that doesn't report contact size gives you no threshold to use.
Revision: key points
- Pixel eraser: clears paint, can’t undo a stroke. Stroke eraser: removes objects. Partial eraser: cuts them.
- Test the segment between pen samples, padded by the eraser’s radius; testing samples loses strokes a fast pen crossed.
fromSegmentAndPaddingmakes a rectangle of the segment’s length plus 2 × padding by 2 × padding.- Ink’s
PartitionedMeshhas a static R-tree over its triangles; a query tests bounds, then triangles exactly, andintersectsstops at the first. - Coverage sums whole triangle areas, so a threshold above zero depends on triangle size.
- Ink 1.0.0 indexes one stroke; the page’s index is yours: a grid absorbs removals, a static R-tree is rebuilt.
- Cut by segments drops whole segments (up to a sample too much on each side); cut at the edge by finding where the path enters and leaves the eraser;
Stroke.subtractis an experimental 1.1 alpha. - An erase is one undo step, with the removed strokes’ positions and the added pieces.
Cheat sheet
Each concept in a few words.
| Concept | In a few words |
|---|---|
| Pixel eraser | Clears paint; can’t undo a stroke. |
| Stroke eraser | Removes whole stroke objects. |
| Partial eraser | Cuts strokes and keeps the pieces. |
| Tunnelling | A fast pen skips a stroke that lies between two samples. |
| Swept rectangle | The segment between samples, padded by the eraser radius. |
| Hit test | Does the eraser touch this shape? |
| Coverage | Share of a mesh’s area in the triangles touched (whole triangles). |
| R-tree | A tree of bounding boxes; whole branches get skipped. |
| Static R-tree | Built once; changing the page means building it again. |
| Grid index | Cells list their strokes; removing one is cheap. |
| Undo step | One gesture: strokes removed, with positions, and the pieces added. |
Read next
- References: Geometry APIs, the Ink releases and the Ink source
- The papers: Guttman, “R-trees: a dynamic index structure for spatial searching” (1984), and Leutenegger, Lopez and Edgington, “STR: a simple and efficient algorithm for R-tree packing” (1997)
- The book: Christer Ericson, Real-Time Collision Detection (2004), for segment-segment and swept tests
- Where real software uses this: Jetpack Ink’s geometry module, which the geometry page describes as the tools for selection and erasers
Search terms that find more: swept collision detection, tunnelling continuous collision detection, R-tree Sort-Tile-Recursive, uniform grid spatial hashing, segment segment distance, androidx.ink Intersection intersects, Stroke.subtract, polygon clipping stroke eraser.
The fine print
The excerpts are from the jetpack-1.0.0 tag of google/ink and the Kotlin sources of androidx.ink 1.0.0, and, for subtract and split, from the 1.1.0-alpha11 sources, which I read and did not compile or run; the library excerpts (marked library source)
are not app code. The Kotlin snippets compile against androidx.ink 1.0.0 and were linted at minSdk 26; they were not run on a device. The lab is a TypeScript model. Its R-tree reproduces the library’s layouts for 5, 12 and 16 points and its node counts, and
its coverage function reproduces the library’s tests on the four-triangle shape; its document-level grid and R-tree, its swept rectangle, and both cuts are this guide’s own geometry and have no library vectors to check against, so their tests check the rules and that every way of searching returns the same strokes. The lab counts strokes asked, bounding boxes compared (R-tree branch nodes and leaf boxes, in the document index and in each stroke’s own index), grid cells looked up, triangle tests and R-tree builds, and its partial erasers look for strokes within the centreline radius the cut uses;
there are no timings in it or in this guide, and a count is not a cost: a build, a grid lookup, a box comparison and a triangle test each take different time. The page is 200 synthetic, gently curving strokes, 4 px wide, in a 620 by 350 area; real handwriting and diagrams cluster differently. The pen path is a straight horizontal line, so
its numbers say how a fast stroke across a busy page behaves and not how a scribble does. Palm erasing is described as a design choice, with no platform source. The page was checked in one desktop browser at about 1431 px: the lab was seen in dark after a sweep and in light before one, a drag was sent as synthetic pointer events, and every “Things to try” number was read back from the page, not looked at.
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, 8. Drawing with low latency.