开发者

How do I recognize a mouse click on a line?

开发者 https://www.devze.com 2023-04-08 16:54 出处:网络
I have a WPF application. There is a canvas. I draw line when user drag the mouse over the canvas (from mouse down to mouse up). I take initial point, when mouse is pressed down and final point, when

I have a WPF application. There is a canvas. I draw line when user drag the mouse over the canvas (from mouse down to mouse up). I take initial point, when mouse is pressed down and final point, when user does mouse up. Then I calculate the distance and draw the line in simple mouse down, move and up events.

After drawing many lines on canvas, 开发者_如何学CI click on any one of the line. I want to select the line and show the user that line is selected (like by changing the color of the line). So user can delete it.

Thanks.


Here is a working example: (implementing what Bala suggested in his comment)

private void myCanvas_Loaded(object sender, RoutedEventArgs e)
        {
            Line line = new Line();

            line.MouseDown += new MouseButtonEventHandler(line_MouseDown);
            line.MouseUp   += new MouseButtonEventHandler(line_MouseUp);

            line.Stroke = Brushes.Black;
            line.StrokeThickness = 2;
            line.X1 = 30; line.X2 = 80;
            line.Y1 = 30; line.Y2 = 30;

            myCanvas.Children.Add(line);
        }

void line_MouseUp(object sender, MouseButtonEventArgs e)
        {
            // Change line colour back to normal 
            ((Line)sender).Stroke = Brushes.Black;
        }

void line_MouseDown(object sender, MouseButtonEventArgs e)
        {
            // Change line Colour to something
            ((Line)sender).Stroke = Brushes.Red;
        }

Considering that you already have the logic to add the lines into canvas,

Simply add the two event handlers (as above) for every line that you add.


I would advise you to add a custom MouseDown event handler to your canvas. Indeed, if your lines are very thin, you need to let the user be able to click near a line to select it.

For this, in your custom MouseDown handler, iterate over your lines and do the following:

For each line:

  • Create a rectangle with the length of the line as width and height = max(lineWidth, 10px),
  • Rotate your mouse coordinates around the rectangle center with an angle equals to the line angle (compute it with math.atan2),
  • Check if the new mouse coordinates lie inside the rectangle,
  • If so, select the current lien and break.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号