How Draw rectangle in WPF?

后端 未结 6 561
天涯浪人
天涯浪人 2020-12-30 02:19

I need draw rectangle in canvas. I know how to draw. But I did not get to do so would draw on a 360-degree

Example. blue, lilac, green they are one and the same rect

6条回答
  •  暖寄归人
    2020-12-30 03:10

    You don't really need to rotate as such - just adjust the height, width, and top-left of your rectangle based on your mouse position.

    This is probably a good starting point for you:

    XAML:

    
    
    

    Code Behind:

        private bool _mouseDown = false;
        private Rectangle _current;
        private Point _initialPoint;
    
        private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _mouseDown = (e.ButtonState == MouseButtonState.Pressed) 
                                         && (e.ChangedButton == MouseButton.Left);
            if (!_mouseDown)
                return;
    
            _current = new Rectangle();
            _initialPoint = e.MouseDevice.GetPosition(MyCanvas);
            _current.Fill = new SolidColorBrush(Colors.Blue);
            MyCanvas.Children.Add(_current);
        }
        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (!_mouseDown)
                return;
    
            Point position = e.MouseDevice.GetPosition(MyCanvas);
            _current.SetValue(Canvas.LeftProperty,
                                             Math.Min(position.X, _initialPoint.X));
            _current.SetValue(Canvas.TopProperty,
                                             Math.Min(position.Y, _initialPoint.Y));
            _current.Width = Math.Abs(position.X - _initialPoint.X);
            _current.Height = Math.Abs(position.Y - _initialPoint.Y);
              }
        private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
                _mouseDown = false;
        }
    

提交回复
热议问题