How Draw rectangle in WPF?

后端 未结 6 568
天涯浪人
天涯浪人 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: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.

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

提交回复
热议问题