我在c#中实现了一个Liang Barsky算法,但是有些错误,因为它有时会返回矩形边界之外的点,如下例所示:
p1 =(516,546),p2 =(0,0) R = 0; L = 511; T = 511; B = 0;
我怎么能指出这条线完全在矩形之外
private void LiangBarsky( PointF P1,PointF P2,float R,float L,float T,float B)
{
try
{
float Tmin = 0;
float Tmax = 1;
float Tl, Tr, Tt, Tb;
Tl = (L - P1.X) / (P2.X - P1.X);
Tr = (R - P1.X) / (P2.X - P1.X);
Tt = (T - P1.Y) / (P2.Y - P1.Y);
Tb = (B - P1.Y) / (P2.Y - P1.Y);
if (0 < Tl && Tl < 1.0)
{
if (InnerProduct(P1, P2, new Point(0, 1)) == EnteringPoint)
Tmin = Tl;
else
Tmax = Tl;
test = true;
}
if (0 < Tr && Tr < 1)
{
if (InnerProduct(P1, P2, new Point(0, -1)) == EnteringPoint)
Tmin = Tr;
else
Tmax = Tr;
test = true;
}
if (0 < Tt && Tt < 1)
{
if (InnerProduct(P1, P2, new Point(1, 0)) == EnteringPoint)
Tmin = Tt;
else
Tmax = Tt;
test = true;
}
if (0 < Tb && Tb < 1)
{
if (InnerProduct(P1, P2, new Point(-1, 0)) == EnteringPoint)
Tmin = Tb;
else
Tmax = Tb;
test = true;
}
if ((Tmin < Tmax) /*&& (Tmin!=0 )&&(Tmax!=1)*/)
{
P1 = new PointF((P1.X + (P2.X - P1.X) * Tmin), (P1.Y + (P2.Y - P1.Y) * Tmin));
P2 = new PointF((P1.X + (P2.X - P1.X) * Tmax), (P1.Y + (P2.Y - P1.Y) * Tmax));
Indtxt.BackColor = Color.Blue;
}
else
{
if(P1.Y>T && P1.X>L && P2.X>L && P2.Y>T)
Indtxt.BackColor = Color.Red;
}
}
catch (Exception ex)
{
}
}
private int InnerProduct(PointF LineP1, PointF LineP2, Point NormalVector)
{
PointF P1_P2 = new PointF(LineP2.X - LineP1.X, LineP2.Y - LineP1.Y);
if (((P1_P2.X * NormalVector.X) + (P1_P2.Y * NormalVector.Y)) <= 0)
return EnteringPoint;//0 as entering point ans 1 as exiting point
else
return ExitingPoint;
}