Search code examples
c#wpflinqinkcanvas

Select strokes from inkcanvas within a rectangle by program


I have an InkCanvas with strokes present. I wish to use only the strokes, or part of the strokes, that fall within a given region. In short, I wish to clip any ink outside of this region. I can't figure out how to cast this correctly:

            Rect r = new Rect(100,100,100,100);

            StrokeCollection x = InkCanvas.Strokes
                .Select(s => s.GetClipResult(r));

Solution

  • LINQ method Select<T>() returns an IEnumerable<T> and you are attempting to assign it to x which is not IEnumerable<T> type. so the correct syntax would be

    IEnumerable<StrokeCollection> x = InkCanvas.Strokes.Select(s => s.GetClipResult(r));
    

    and if you wish to have to have first collection then x.First() or x.FirstOrDefault() will return the first StrokeCollection from the IEnumerable<StrokeCollection> where former will throw exception if it is empty and latter will return null which is default for reference type StrokeCollection.

    Retrieve all strokes in a new stroke collection

    the LINQ can be modified to

    StrokeCollection strokes = new StrokeCollection(InkCanvas.Strokes.SelectMany(s => s.GetClipResult(r)));
    

    this will retrieve all the strokes from the clip region and create a new StrokeCollection with them.