Question

I'm working on a practice application that adds blue squares to a canvas when you click inside the canvas. One of the requirements is that the shape is added at that point with the mouse representing the center of the new shape.

By default, the click point of the mouse will be the top left of the square. Is there a way to make the square spawn from the center of the mouse click instead of the top right?

This is how i currently add my squares to the canvas:

    private void canvasArea_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {

        Shape Rendershape = null;

        switch (Shape1)
        {
            case SelectedShape.Rectangle:
                Rendershape = new Rectangle() 
                { 
                    Fill = Brushes.Blue, 
                    Height = num1, 
                    Width = num2
                };
                break;
            default:
                return;
        }

        Canvas.SetLeft(Rendershape, e.GetPosition(canvasArea).X);
        Canvas.SetTop(Rendershape, e.GetPosition(canvasArea).Y);
        canvasArea.Children.Add(Rendershape);
    }
Was it helpful?

Solution

All you need to do is shift the rectangle by half the rectangle's width and height, see following code:

Canvas.SetLeft(Rendershape, e.GetPosition(canvasArea).X - ( Rendershape.Width / 2.0 ) );
Canvas.SetTop(Rendershape, e.GetPosition(canvasArea).Y - ( Rendershape.Height / 2.0 ) );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top