Compartir a través de


Back-of-pen Erasing in Silverlight

As addendum to my previous post Erasing Ink in Silverlight 2 I want to show how to enable back-of-pen erasing for users with a compatible stylus device (e.g. on a Tablet PC or with an external Graphics Tablet).

The key that enables this scenario is the StylusDevice.Inverted property. It reports during mouse events whether the front-of-pen (stylus) or back-of-pen (eraser) is being used. The app can then switch into inking or erasing mode automatically, according to this value.

Here is the code-behind you need to add for an InkPresenter to enable this scenario:

public partial class Page : UserControl

{

    public Page()

    {

        InitializeComponent();

    }

    private void inkPresenter_MouseLeftButtonDown(object sender,
MouseButtonEventArgs e)

    {

        inkPresenter.CaptureMouse();

        if (e.StylusDevice.Inverted == false)

        {

            // ink mode

            newStroke =

               new Stroke(e.StylusDevice.GetStylusPoints(inkPresenter));

            inkPresenter.Strokes.Add(newStroke);

        }

        else

        {

            // erase mode

            erasePoints = e.StylusDevice.GetStylusPoints(inkPresenter);

        }

    }

    private void inkPresenter_MouseMove(object sender, MouseEventArgs e)

    {

        if (e.StylusDevice.Inverted == false)

        {

            // ink mode

            if (newStroke != null)

            {

                newStroke.StylusPoints.Add(

                    e.StylusDevice.GetStylusPoints(inkPresenter));

            }

        }

        else if (e.StylusDevice.Inverted == true)

        {

            // erase mode

            if (erasePoints != null)

            {

     erasePoints.Add(
e.StylusDevice.GetStylusPoints(inkPresenter));

                StrokeCollection hitStrokes =
inkPresenter.Strokes.HitTest(erasePoints);

                foreach (Stroke hitStroke in hitStrokes)

                {

                  inkPresenter.Strokes.Remove(hitStroke);

                }

            }

        }

    }

    private void inkPresenter_MouseLeftButtonUp(object sender,
MouseButtonEventArgs e)

    {

        inkPresenter.ReleaseMouseCapture();

        erasePoints = null;

        newStroke = null;

    }

    private StylusPointCollection erasePoints = null;

    private Stroke newStroke = null;

}