The code below provided the functionality for me which you can adapt to work for you.
The enumeration is a list of all the different shapes you want the user to be able to draw. The buttons you have implemented should set the activeShapeType value. Add your methods from drawing rectangles, circle, etc to the switch statement in the Canvas_MouseLeftButtonDown event.
The right click event will allow the user to cancel a line they are drawing before the second click.
public bool IsFirstPoint = true;
public Point StartPoint;
public enum ShapeType
{
line,
circle,
rectangle
}
public ShapeType activeShapeType = ShapeType.line;
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (IsFirstPoint)
{
StartPoint = (Mouse.GetPosition(Surface));
IsFirstPoint = false;
}
else
{
switch (activeShapeType)
{
case ShapeType.line:
Line line = new Line() { X1 = StartPoint.X, Y1 = StartPoint.Y, X2 = Mouse.GetPosition(Surface).X, Y2 = Mouse.GetPosition(Surface).Y, Stroke = Brushes.Black };
Surface.Children.Add(line);
break;
case ShapeType.rectangle:
/*Your code to draw rectangle here*/
break;
}
IsFirstPoint = true;
}
}
private void Surface_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
IsFirstPoint = true;
}
This code should add the temporary line while moving the mouse.
private void Surface_MouseMove(object sender, MouseEventArgs e)
{
if (!IsFirstPoint)
{
if (Surface.Children.Count > 0)
{
var child = (from c in Surface.Children.OfType<FrameworkElement>()
where "tempLine".Equals(c.Tag)
select c).First();
if (child != null)
{
Surface.Children.Remove(child);
}
}
switch (activeShapeType)
{
case ShapeType.line:
Line line = new Line() { Tag="tempLine", X1 = StartPoints.X, Y1 = StartPoints.Y, X2 = Mouse.GetPosition(Surface).X, Y2 = Mouse.GetPosition(Surface).Y, Stroke = Brushes.Black };
Surface.Children.Add(line);
return;
}
}
}