How Draw rectangle in WPF?

Unless you need a rotated rectangle I wouldn't bother using transforms. Just set Left and Top to the minimum x and y and width to max-x and height maxy-y.

<Canvas x:Name="canvas" MouseDown="Canvas_MouseDown" MouseMove="Canvas_MouseMove" MouseUp="Canvas_MouseUp" Background="Transparent" />
private Point startPoint;
private Rectangle rect;

private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
    startPoint = e.GetPosition(canvas);

    rect = new Rectangle
    {
        Stroke = Brushes.LightBlue,
        StrokeThickness = 2
    };
    Canvas.SetLeft(rect,startPoint.X);
    Canvas.SetTop(rect,startPoint.Y);
    canvas.Children.Add(rect);
}

private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
    if(e.LeftButton == MouseButtonState.Released || rect == null)
        return;

    var pos = e.GetPosition(canvas);

    var x = Math.Min(pos.X, startPoint.X);
    var y = Math.Min(pos.Y, startPoint.Y);

    var w = Math.Max(pos.X, startPoint.X) - x;
    var h = Math.Max(pos.Y, startPoint.Y) - y;

    rect.Width = w;
    rect.Height = h;

    Canvas.SetLeft(rect, x);
    Canvas.SetTop(rect, y);
}

private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
    rect = null;
}

Steps:

  1. On MouseLeftButtonDown: if you are not rotating: add a rectangle with its top left corner at the coordinates of the mouse and its height and width calculated by the difference between the top corner and the mouse coordinates. Set a boolean to true to indicate that you are drawing. if you are rotating: stop rotating by setting the rotating boolean to false.

  2. On MouseMove: check if the left mouse button is still down and you are drawing (boolean from previous step). recalculate the width and height of the rectangle. If you are rotating adjust the rotation of the rectangle by calculating the angle between the point where you released the button, the RenderTransformOrigin and the current location of the mouse. (Use Vector.AngleBetween()

  3. On MouseLeftButtonUp: if drawing is true set the drawing boolean to false and set a rotating boolean to true.

This flow will allow you to click (set a corner of the rectangle), drag and release to set the opposite corner, move the mouse to rotate the rectangle and click to fix the rectangle.

Place and rotate the rectangle by using RenderTransform: that will make things much easier than setting margins or Canvas.Left on the rectangle.

Let me know if you need help.

Tags:

C#

Wpf