gpt4 book ai didi

c# - 如何知道一条线是否与矩形相交

转载 作者:可可西里 更新时间:2023-11-01 07:49:05 27 4
gpt4 key购买 nike

我已经检查过这个问题,但答案对我来说非常大:

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

是否有任何 .NET 方法可以知道由两点定义的线是否与矩形相交?

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

提前致谢。

最佳答案

    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;
}

关于c# - 如何知道一条线是否与矩形相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5514366/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com