I'm trying to learn wpf. The problem is that the line I'm drawing extends beyond the canvas. This only happens when the left mouse button is pressed and before that the mouse cursor was hovering over the canvas.
Code .cs
ArrayPoints arrayPoints = new ArrayPoints(2);
private void Canvas_mouse_move(object sender, MouseEventArgs e)
{
if(e.MouseDevice.LeftButton == MouseButtonState.Pressed)
{
arrayPoints.SetPoints(new Point(e.GetPosition(Canvas).X, e.GetPosition(Canvas).Y));
if (arrayPoints.GetIndex() >= 2)
{
Canvas.Children.Add(new Line
{
X1 = arrayPoints.GetPoints()[0].X,
Y1 = arrayPoints.GetPoints()[0].Y,
X2 = arrayPoints.GetPoints()[1].X,
Y2 = arrayPoints.GetPoints()[1].Y,
StrokeStartLineCap = PenLineCap.Round,
StrokeEndLineCap = PenLineCap.Round,
StrokeThickness = 10,
Stroke = Brushes.Red
});
arrayPoints.SetPoints(new Point(e.GetPosition(Canvas).X, e.GetPosition(Canvas).Y));
}
}
}
private void Canvas_left_button_up(object sender, MouseButtonEventArgs e)
{
arrayPoints.ResetPoints();
}
xaml
<Window x:Class="Paint.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Paint"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Background="#404040">
<Canvas x:Name="Canvas" Background ="White" Margin="30" MouseMove="Canvas_mouse_move" MouseLeftButtonUp="Canvas_left_button_up" MouseLeave="Canvas_mouse_leave"/>
</Grid>
CodePudding user response:
I solved the problem. Canvas is the only layout element that allows child elements to be rendered outside of bounds. To avoid this, you need to write this code.
ClipToBounds="True"