问题
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.
回答1:
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));
}
回答2:
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.
来源:https://stackoverflow.com/questions/1479665/easiest-way-to-draw-a-sequence-of-points-in-wpf-from-code