How Draw rectangle in WPF?

后端 未结 6 528
天涯浪人
天涯浪人 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 02:59
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    
    namespace SilverlightApplication1
    {
        public partial class MainPage : UserControl
        {
            public MainPage()
            {
                // Required to initialize variables
                InitializeComponent();
    
                mainCanvas.MouseLeftButtonDown+=new System.Windows.Input.MouseButtonEventHandler(MainPage_MouseLeftButtonDown);
                mainCanvas.MouseLeftButtonUp+=new System.Windows.Input.MouseButtonEventHandler(MainPage_MouseLeftButtonUp);
                mainCanvas.MouseMove+=new System.Windows.Input.MouseEventHandler(MainPage_MouseMove);
    
                SolidColorBrush myBrush = new SolidColorBrush(Colors.Green);
    
                _curRectangle.Rect.Stroke = myBrush;
                _curRectangle.Rect.StrokeThickness = 4;
                _curRectangle.Rect.Fill = myBrush;
            }
    
            private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
            {
                // TODO: Add event handler implementation here.
            }
    
            private void elipse_Click(object sender, System.Windows.RoutedEventArgs e)
            {
                // TODO: Add event handler implementation here.
            }
            RealRect _curRectangle = null;
            private void MainPage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
            {
                _curRectangle = new RealRect((int)e.GetPosition(sender as Canvas).X, (int)e.GetPosition(sender as Canvas).Y, false);
                mainCanvas.Children.Insert(0, _curRectangle.Rect);
                _curRectangle.StartRect();
            }
    
            private void MainPage_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
            {
                if (_curRectangle != null)
                {
                    _curRectangle.ClearStartTemp();
                    _curRectangle = null;
                }
    
            }
    
            private void MainPage_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
            {
                if (_curRectangle != null)
                {
                    _curRectangle.EndX = (int)e.GetPosition(sender as Canvas).X;
                    _curRectangle.EndY = (int)e.GetPosition(sender as Canvas).Y;
                    _curRectangle.MakeReal();
                }
    
                //exampleRectangle.Rect.Width =  - Canvas.GetLeft(exampleRectangle.Rect);
                //exampleRectangle.Rect.Height =  - Canvas.GetTop(exampleRectangle.Rect);
            }
        }
    }
    

    Work class

    using System.Windows.Shapes;
    using System.Windows.Controls;
    using System.Windows;
    namespace SilverlightApplication1
    {
        public struct Point
        {
            public static readonly Point Empty;
            public Point(int x, int y) { _x = x; _y = y; }
            int _x;
    
            public int X
            {
                get { return _x; }
                set { _x = value; }
            }
            int _y;
    
            public int Y
            {
                get { return _y; }
                set { _y = value; }
            }
        }
        public class RealRect
        {
            Rectangle mRect = new Rectangle();
    
            #region Class Local Variables
    
            private SilverlightApplication1.Point mStart;
    
            public SilverlightApplication1.Point MStart
            {
                get { return mStart; }
                set { mStart = value; }
            }
            private SilverlightApplication1.Point mEnd;
            private SilverlightApplication1.Point mRealStart;
            private SilverlightApplication1.Point mRealEnd;
            private System.Windows.Size mRealSize;
            private bool isStatus = false;
    
            public bool IsStatus
            {
                get { return isStatus; }
                set { isStatus = value; }
            }
            private SilverlightApplication1.Point mTempPoint;
    
            #endregion
    
    
            public RealRect(int x, int y, bool start)
            {
                mTempPoint = new SilverlightApplication1.Point(x, y);
                IsStatus = false;
                mEnd = Point.Empty;
                mRealEnd = Point.Empty;
            }
            public void ClearStartTemp()
            {
                IsStatus = false;
                mTempPoint = Point.Empty;
            }
            public void StartRect()
            {
                IsStatus = true;
                mStart = mTempPoint;
                mRealStart = mTempPoint;
    
            }
    
    
            /// <summary>
            /// Ending X Value of rectangle
            /// </summary>
            public int EndX
            {
                set { mEnd.X = value; }
            }
    
            /// <summary>
            /// Ending Y Value of rectangle
            /// </summary>
            public int EndY
            {
                set { mEnd.Y = value; }
            }
    
            /// <summary>
            /// Get the corrected rectangle
            /// </summary>
            public Rectangle Rect
            {
                get
                {
                    MakeReal();
    
                    return mRect;
    
                }
            }
    
            public void MakeReal()
            {
                //Started top left, ended bottom right
                if (mEnd.X > mStart.X && mEnd.Y > mStart.Y)
                {
                    mRealStart = mStart;
                    mRealEnd = mEnd;
                    mRealSize = new Size(mRealEnd.X - mRealStart.X, mRealEnd.Y - mRealStart.Y);
                   // return;
                }
    
                //Started bottom right, ended top left
                else if (mEnd.X < mStart.X && mEnd.Y < mStart.Y)
                {
                    mRealEnd = mStart;
                    mRealStart = mEnd;
                    mRealSize = new Size(mRealEnd.X - mRealStart.X, mRealEnd.Y - mRealStart.Y);
                   // return;
                }
    
                //Started top right left, ended bottom left
                else if (mEnd.X < mStart.X && mEnd.Y > mStart.Y)
                {
                    mRealStart.X = mEnd.X;
                    mRealStart.Y = mStart.Y;
                    mRealEnd.X = mStart.X;
                    mRealEnd.Y = mEnd.Y;
                    mRealSize = new Size(mRealEnd.X - mRealStart.X, mRealEnd.Y - mRealStart.Y);
                   // return;
                }
    
                //Started bottom left, ended top right
                else if (mEnd.X > mStart.X && mEnd.Y < mStart.Y)
                {
                    mRealStart.X = mStart.X;
                    mRealStart.Y = mEnd.Y;
                    mRealEnd.X = mEnd.X;
                    mRealEnd.Y = mStart.Y;
                    mRealSize = new Size(mRealEnd.X - mRealStart.X, mRealEnd.Y - mRealStart.Y);
                   // return;
                }
                Canvas.SetLeft(mRect, mRealStart.X);
                Canvas.SetTop(mRect, mRealStart.Y);
                mRect.Width = mRealSize.Width;
                mRect.Height = mRealSize.Height;
            }
        }
    
    
    }
    
    0 讨论(0)
  • 2020-12-30 03:01

    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.

    0 讨论(0)
  • 2020-12-30 03:02

    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;
    }
    
    0 讨论(0)
  • 2020-12-30 03:02

    Maybe I'm wrong but I think this can work :

          <Rectangle Width="200" Height="50" Fill="Black">
            <Rectangle.RenderTransform>
                <RotateTransform CenterX="0" CenterY="0" Angle="45"></RotateTransform>
            </Rectangle.RenderTransform>
        </Rectangle>
    
    0 讨论(0)
  • 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:

    <Canvas x:Name="MyCanvas"
            Background="White"
            IsHitTestVisible="True"
            MouseDown="Canvas_MouseDown"
            MouseMove="Canvas_MouseMove"
            MouseUp="Canvas_MouseUp">
    </Canvas>
    

    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;
        }
    
    0 讨论(0)
  • 2020-12-30 03:19

    If someone is interested, this is solution for UWP. (based on @Kris answer).

    It works for mouse, touch and pen.

    Code behind:

    private Point startPoint;
    private Rectangle rect;
    
    private void canvas_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        startPoint = e.GetCurrentPoint(canvas).Position;
        rect = new Rectangle()
        {
            Stroke = new SolidColorBrush(Colors.LightCoral),
            StrokeThickness = 5
        };
    
        Canvas.SetLeft(rect, startPoint.X);
        Canvas.SetTop(rect, startPoint.Y);
        canvas.Children.Add(rect);
    }
    
    private void canvas_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        if (!e.Pointer.IsInContact || rect == null)
            return;
    
        var pos = e.GetCurrentPoint(canvas).Position;
    
        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_PointerReleased(object sender, PointerRoutedEventArgs e)
    {
        rect = null;
    }
    

    XAML:

    <Canvas x:Name="canvas" PointerPressed="canvas_PointerPressed" PointerMoved="canvas_PointerMoved" PointerReleased="canvas_PointerReleased" Background="Transparent" />
    
    
    0 讨论(0)
提交回复
热议问题