How to tell if a line intersects a polygon in C#?

后端 未结 4 1901
悲&欢浪女
悲&欢浪女 2020-12-31 18:17

I have a question very similar to this:

How to know if a line intersects a plane in C#?

I am searching for a method (in C#) tha

4条回答
  •  没有蜡笔的小新
    2020-12-31 18:34

    There is no builtin code for edge detection built into the .NET framework.

    Here's code (ported to C#) that does what you need (the actual algorithm is found at comp.graphics.algorithms on Google groups) :

    public static PointF FindLineIntersection(PointF start1, PointF end1, PointF start2, PointF end2)
    {
        float denom = ((end1.X - start1.X) * (end2.Y - start2.Y)) - ((end1.Y - start1.Y) * (end2.X - start2.X));
    
        //  AB & CD are parallel 
        if (denom == 0)
            return PointF.Empty;
    
        float numer = ((start1.Y - start2.Y) * (end2.X - start2.X)) - ((start1.X - start2.X) * (end2.Y - start2.Y));
    
        float r = numer / denom;
    
        float numer2 = ((start1.Y - start2.Y) * (end1.X - start1.X)) - ((start1.X - start2.X) * (end1.Y - start1.Y));
    
        float s = numer2 / denom;
    
        if ((r < 0 || r > 1) || (s < 0 || s > 1))
            return PointF.Empty;
    
        // Find intersection point
        PointF result = new PointF();
        result.X = start1.X + (r * (end1.X - start1.X));
        result.Y = start1.Y + (r * (end1.Y - start1.Y));
    
        return result;
     }
    

提交回复
热议问题