计算机图形学常用算法实现8 中点分割裁剪算法

这种方法使用了二分法查找边界,优化了Cohen-Sutherland方法,减小了讨论的数量。
代码中边界范围是200,200到400,400
代码如下:

int encode(Point p)
{
    int code = 0;
    if (p.Y > 400)
        code += 8;
    if (p.Y < 200)
        code += 4;
    if (p.X > 400)
        code += 2;
    if (p.X < 200)
        code += 1;
    return code;
}
//找出p1和p2之间边界的交点
Point findIntersection(Point p1,Point p2)
 {
     Point pmid = new Point();
     pmid.X = (p1.X + p2.X) / 2;
     pmid.Y = (p1.Y + p2.Y) / 2;
     if (distance(pmid, p1) < 1.5)
         return pmid;  
     int code1 = encode(p1);
     int code2 = encode(p2);
     int codemid = encode(pmid);
     if(code1==0)
         if(codemid == 0)
             return findIntersection(pmid, p2);
         else
             return findIntersection(p1, pmid);
     if (code2 == 0)
         if (codemid == 0)
             return findIntersection(pmid, p1);
         else
             return findIntersection(p2, pmid);
     return pmid;
 }
void midLineClip(Point p1,Point p2)
{
   Graphics g = this.CreateGraphics();
   Pen p = new Pen(Brushes.Black);
   int code1 = encode(p1);
   int code2 = encode(p2);
   if ((code1 & code2) != 0)
       return;
   //存在一个点在裁剪框内
   if (code1 == 0 && code2 == 0)
       g.DrawLine(p, p1, p2);
   else
   {
       if (code1 == 0)
           g.DrawLine(p, p1, findIntersection(p1, p2));
       else if (code2 == 0)
           g.DrawLine(p, findIntersection(p1, p2), p2);
       else
       {
           midLineClip(p1,new Point((p1.X+p2.X)/2,(p1.Y+p2.Y)/2));
           midLineClip(new Point((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2),p2);

       }
   }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43813453/article/details/84589594