How do I recognize a mouse click on a line?

时光怂恿深爱的人放手 提交于 2019-12-23 05:45:13

问题


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, I 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.


回答1:


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.




回答2:


Take a look at this project: http://www.codeproject.com/KB/WPF/WPF_DrawTools.aspx




回答3:


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.


来源:https://stackoverflow.com/questions/7556493/how-do-i-recognize-a-mouse-click-on-a-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!