简体   繁体   English

C#WPF - 鼠标单击从中心点击产生的形状

[英]C# WPF — Mouse click spawning shape from the center of the click

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);
    }

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 ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM