Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
30 views
in Technique[技术] by (71.8m points)

c# - How Draw rectangle in WPF?

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 rectangle, I changed the color for example Red point is start position rectangle.

enter image description here

EDIT:

My actions:

LeftMouseDown in x=50;y=50 (press) MoveMouse to 100;100 - now it works MoveMouse to 30;150 or MoveMouse to 10;10 - Now I can not do this, but I need it

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...