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.
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
Creating a RectangleThe Rectangle element in XAML creates a rectangle shape. The following code snippet creates a rectangle by setting its width and height properties to 200 and 100 respectively. The code also sets the black stroke of width 4.
WPF provides various shapes & drawings to generate 2D graphics. We will learn shapes such as Line, Ellipse, Rectangle, Path, Polyline & Polygon.
To draw a line, create a Line element. Use its X1 and Y1 properties to set its start point; and use its X2 and Y2 properties to set its end point. Finally, set its Stroke and StrokeThickness because a line without a stroke is invisible. Setting the Fill element for a line has no effect, because a line has no interior.
Use its Stroke property to specify the Brush that is used to paint the outline of the ellipse. The StrokeThickness property specifies the thickness of the ellipse outline. To draw a circle, make the Width and Height of the Ellipse element equal to each other.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With