本文介绍了如何知道,如果一条线相交的矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经签出了这个问题,但答案是非常大的,我:

How要知道,如果一条线相交平面在C#中? - 基本的2D几何

有没有.NET方法知道,如果两点定义的直线相交的矩形?

 公共布尔相交点(A点,B点,矩形r)
{
   如果线相交的矩形//返回true
   //否则为false
}
 

在此先感谢。

解决方案

 公共静态布尔LineIntersectsRect(点P1,P2点,矩形r)
    {
        返回LineIntersectsLine(P1,P2,新点(RX,RY),新点(RX + r.Width,RY))||
               LineIntersectsLine(P1,P2,新点(RX + r.Width,RY),新点(RX + r.Width,RY + r.Height))||
               LineIntersectsLine(P1,P2,新点(RX + r.Width,RY + r.Height),新的点(RX,RY + r.Height))||
               LineIntersectsLine(P1,P2,新点(RX,RY + r.Height),新的点(RX,RY))||
               (r.Contains(P1)及&安培; r.Contains(P2));
    }

    私有静态布尔LineIntersectsLine(点l1p1,点l1p2,点l2p1,点l2p2)
    {
        浮Q =(l1p1.Y  -  l2p1.Y)*(l2p2.X  -  l2p1.X) - (l1p1.X  -  l2p1.X)*(l2p2.Y  -  l2p1.Y);
        浮D =(l1p2.X  -  l1p1.X)*(l2p2.Y  -  l2p1.Y) - (l1p2.Y  -  l1p1.Y)*(l2p2.X  -  l2p1.X);

        如果(D == 0)
        {
            返回false;
        }

        浮动R = Q / D组;

        Q =(l1p1.Y  -  l2p1.Y)*(l1p2.X  -  l1p1.X) - (l1p1.X  -  l2p1.X)*(l1p2.Y  -  l1p1.Y);
        一个float = Q / D;

        如果(R< 0 || R> 1 || S< 0 || S> 1)
        {
            返回false;
        }

        返回true;
    }
 

I have checked out this question, but the answer is very large for me:

How to know if a line intersects a plane in C#? - Basic 2D geometry

Is there any .NET method to know if a line defined by two points intersects a rectangle?

public bool Intersects(Point a, Point b, Rectangle r)
{
   // return true if the line intersects the rectangle
   // false otherwise
}

Thanks in advance.

解决方案
    public static bool LineIntersectsRect(Point p1, Point p2, Rectangle r)
    {
        return LineIntersectsLine(p1, p2, new Point(r.X, r.Y), new Point(r.X + r.Width, r.Y)) ||
               LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y), new Point(r.X + r.Width, r.Y + r.Height)) ||
               LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y + r.Height), new Point(r.X, r.Y + r.Height)) ||
               LineIntersectsLine(p1, p2, new Point(r.X, r.Y + r.Height), new Point(r.X, r.Y)) ||
               (r.Contains(p1) && r.Contains(p2));
    }

    private static bool LineIntersectsLine(Point l1p1, Point l1p2, Point l2p1, Point l2p2)
    {
        float q = (l1p1.Y - l2p1.Y) * (l2p2.X - l2p1.X) - (l1p1.X - l2p1.X) * (l2p2.Y - l2p1.Y);
        float d = (l1p2.X - l1p1.X) * (l2p2.Y - l2p1.Y) - (l1p2.Y - l1p1.Y) * (l2p2.X - l2p1.X);

        if( d == 0 )
        {
            return false;
        }

        float r = q / d;

        q = (l1p1.Y - l2p1.Y) * (l1p2.X - l1p1.X) - (l1p1.X - l2p1.X) * (l1p2.Y - l1p1.Y);
        float s = q / d;

        if( r < 0 || r > 1 || s < 0 || s > 1 )
        {
            return false;
        }

        return true;
    }

这篇关于如何知道,如果一条线相交的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 14:32