LiangBarsky算法的线裁剪c#

时间:2011-07-14 14:43:33

标签: c# algorithm math graphics clipping

我在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;
    }
  • 我将algorith翻译成了之前的代码,所以我可能会错过一些概念

1 个答案:

答案 0 :(得分:2)

看到此链接,它会显示所有带有代码c#

的算法

http://pastebin.com/NA01gacf