Search code examples
c#uwpwin2d

Drawing editable and selectable shapes with Win2D?


I've used System.Windows.Shapes before to add Shapes to Canvas-controls. They can be used like objects and the visuals change as I edit the fields. I can also add event handlers for clicks etc.

I'd need this kind of functionality by using Win2D. Is there any easy way?

I'm trying to create a simple app like this:

  • User can draws shapes to canvas
  • Shapes can be selected and highlighted by clicking
  • Selected shapes's can be manipulated (color, opacity, width, height, position etc)
  • Shapes can be layered over each other (Z-index)

I guess one way would be to create custom Shape classes with Draw-methods. I'd then only manipulate the object - and the changes would reflect to visuals thru the Draw-method. On each canvas invalidation, the objects would be drawn again.

Any ideas?


Solution

  • Win2D can help you with hit-testing. With geometries that have a fill color, then use CanvasGeometry.FillContainsPoint(...) and for geometries that only have an outline/stroke, use CanvasGeometry.StrokeContainsPoint(...). Using these two methods, you'll get accurate hit-testing. Using bounds is not accurate for non-rectangular shapes, including rotated rectangles.

    For z-indexing, then you have to keep track of the order of your geometries and go through the list from top to bottom until the PointerPoint has hit something.

    If your list of geometries is too large and you notice a lag, then you can start hit-testing using bounds first and if it fails, continue to next item, if it hits, then use the above methods to get an accurate reading.