I'm approaching WPF drawing world (using .NET 4.5 and VS2013) and I'm struggling with the following question: I'd like to draw a polygon on a canvas using mouse click/move events. On the web I saw some static examples(i.e. points carved in XAML/C# code), using WebForms or GDI but that doesn't suites my needs. It would be great if someone could provide a simple example, no need for the fancy stuff (like moving or resizig the polygon).
EDIT: My requirements are exactly the same as the one of the following OP:
Drawing Line to next point in realtime
The answer marked as best is near but not exactly what I need. I tried this:
<Canvas Name="canvas"
MouseMove="Canvas_MouseMove"
MouseLeftButtonDown="Canvas_MouseLeftButtonDown"
MouseLeftButtonUp="Canvas_MouseLeftButtonUp"
MouseRightButtonDown="Canvas_MouseRightButtonDown">
<Canvas.Background>
<SolidColorBrush Color="White" Opacity="0"/>
</Canvas.Background>
</Canvas>
C#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private Polygon p;
private Polyline segment = new Polyline();
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (p == null)
{
var canvas = (Canvas)sender;
var point = e.GetPosition(canvas);
// create new polyline
p = new Polygon();
p.Stroke = Brushes.Black;
p.Points.Add(point);
canvas.Children.Add(p);
// initialize current polyline segment
segment.Stroke = Brushes.Red;
segment.Points.Add(point);
segment.Points.Add(point);
canvas.Children.Add(segment);
}
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (p != null)
{
// update current polyline segment
var canvas = (Canvas)sender;
segment.Points[1] = e.GetPosition(canvas);
segment.Stroke = Brushes.Blue;
}
}
private void Canvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
p = null;
segment.Points.Clear();
canvas.Children.Remove(segment);
}
private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (p != null)
{
var canvas = (Canvas)sender;
segment.Points[1] = e.GetPosition(canvas);
p.Points.Add(segment.Points[1]);
segment.Points[0] = segment.Points[1];
}
}
}
- The code above draws a polygon after each mouse click, I would like to draw it only at the end of the process (let's say after a right click).
- It starts drawing the first line while dragging the mouse, it would be nicer to have "click once to anchor the first point, click on another spot to anchor the second one, draw a line between them etc.".
Aucun commentaire:
Enregistrer un commentaire