1

I need to get an Image from a StrokeCollection, but have no access to the Visual (InkCanvas) itself because of the mvvm structure. Is there possibly an easy way to get this done?

XAML:

<InkCanvas x:Name="paintSurface" Grid.Row="0" Opacity="0.2" Strokes="{Binding Strokes}">
    <InkCanvas.DefaultDrawingAttributes>
        <DrawingAttributes Color="Black" Width="10" Height="10"/>
    </InkCanvas.DefaultDrawingAttributes>
</InkCanvas>

Viewmodel:

private StrokeCollection _strokes;
public StrokeCollection Strokes {
    get => _strokes;
    set => SetProperty(ref _strokes, value);
} 

Now i just want to convert the StrokeCollection into some form of processable Image, wether it is a Bitmap, BitmapImage, Mat, EmguCV Image, is not important. Thx in advance :)

KilianS
  • 21
  • 7
  • Did you have a look at this post? https://stackoverflow.com/questions/49231819/saving-strokes-as-an-image-using-mvvm – trix Oct 16 '20 at 13:12
  • You could rendertargetbitmap in the view. You "just" need to trigger that from the viewmodel or tell the viewmodel it's done. You probably won't want to exercise automated tests against a chunk of ui anyhow, but you couod encapsulate the code behind in a behavior if you wanted to re use it. Do you need pictures? You could extract the points out the strokes and build geometries use as data for paths. – Andy Oct 16 '20 at 17:47

1 Answers1

1

I solved my Problem by handing the StrokeCollection to a helper class where i just create a new InkCanvas, add the Strokes (from the Original InkCanvas in the UI) and render it.

public static Bitmap convertStrokestoImage(StrokeCollection strokes, int width, int height)
    {
        InkCanvas InkyStinky = new InkCanvas();
        InkyStinky.RenderSize = new System.Windows.Size(width, height);
        InkyStinky.Strokes.Add(strokes);
        RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
        bmp.Render(InkyStinky);
        MemoryStream stream = new MemoryStream();
        BitmapEncoder encoder = new BmpBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bmp));
        encoder.Save(stream);
        Bitmap b = new Bitmap(stream);
        return b;
    }
KilianS
  • 21
  • 7