Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to draw a sequence of points in WPF from code

Tags:

wpf

drawing

point

I'd like to create a WPF app that traces the location of the mouse cursor, updating the image in the MouseMove event handler. My original thought was to create a GeometryDrawing and then add paths to that but I'm struggling with how to wire this up in code (though the Xaml for GeometryDrawings seems straightforward). What's the easiest way to wire this stuff up - its just for debugging so I'm not concerned about efficiency.

like image 541
James Cadd Avatar asked Sep 25 '09 21:09

James Cadd


2 Answers

What about just using Polyline?

Here's the xaml:

<Window
    x:Class="CursorLine.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1"
>
    <Canvas x:Name="canvas" Background="#00FFFFFF" MouseMove="Canvas_MouseMove">
        <Polyline x:Name="polyline" Stroke="DarkGreen" StrokeThickness="3"/>
    </Canvas>
</Window>

Here's the code behind:

private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
    polyline.Points.Add(e.GetPosition(canvas));
}
like image 126
cplotts Avatar answered Nov 18 '22 19:11

cplotts


Use a GeometryGroup. This can have multiple child geometries: in your case you would add an EllipseGeometry for each mouse move point, centred on the mouse location. So something like:

private GeometryGroup _allMousePoints = new GeometryGroup();

void OnMouseMove(...)
{
  _allMousePoints.Children.Add(
    new EllipseGeometry {
      Center = mouseLocation,
      RadiusX = 3,
      Radius Y = 3
    });
}

You can now use _allMousePoints as the Geometry of a GeometryDrawing or the Data of a Path.

like image 32
itowlson Avatar answered Nov 18 '22 17:11

itowlson