Erasing Ink in Silverlight 2

Another frequently asked question around inking in Silverlight is about erasing Ink strokes after they have been collected or loaded. Unlike WPF or the Tablet SDK for COM & Winforms, Silverlight does not come with controls that have built-in eraser modes in the box. However, with a little bit of code-behind you can implement those modes and adjust them to your specific needs. The key APIs you will need for this are StrokeCollection.HitTest() and Stroke.HitTest(). Both APIs take a collection of StylusPoints as input and they return a value indicating whether or not the ink stroke(s) have been hit. Based on that you can then modify your collection accordingly to represent the result of the erase operation. Popular inking apps (e.g. Windows Journal) offer two different modes of erasing:

Erase By Stroke:
Implementing this mode is fairly straight forward. Just pass the stylus points collected along the eraser path into the HitTest() method of your collection of ink strokes and the API will tell you which strokes to remove from your collection.

Erase By Point:
This one takes a little more effort to get right. We start like above, but then we don't remove the hit strokes. Instead, we figure out which segment of the stroke was hit (by using the Stroke.HitTest() API) and then we split the stroke by removing that segment.

I have attached a sample that implements both modes. You can also check out a live version of the sample below. The simplistic implementation of "Erase By Point" in the sample leaves some areas of improvements for the reader (or for a future blog post). Most notably, the size the chunk erased in this mode is not very consistent as it depends on several factors (distance points, location of the hit point, thickness of the stroke, etc.). A good improvement would be to add some logic that ensures the eraser always cuts a consistent chunk out of the ink strokes.

InkEraseSample.zip