How do I detect click on a line in Windows Forms

后端 未结 2 880
陌清茗
陌清茗 2020-12-19 21:50

I have a winforms application

Here is my code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using S         


        
2条回答
  •  情话喂你
    2020-12-19 22:39

    Using GraphicsPath.IsOutlineVisible method you can determine whether the specified point is under the outline of the path when drawn with the specified Pen. You can set width of the pen.

    So you can create a GraphicsPath and then add a line using GraphicsPath.AddLine to the path and check if the path contains the point.

    Example:

    The below method, checks if the p is on the line with end points p1 and p2 using the specified width.

    You can use wider width to increase the tolerance or if the line is wider than 1:

    //using System.Drawing;
    //using System.Drawing.Drawing2D;
    bool IsOnLine(Point p1, Point p2, Point p, int width = 1)
    {
        using (var path = new GraphicsPath())
        {
            using (var pen = new Pen(Brushes.Black, width))
            {
                path.AddLine(p1, p2);
                return path.IsOutlineVisible(p, pen);
            }
        }
    }
    

提交回复
热议问题