Drawing lines with Bresenham's Line Algorithm

前端 未结 3 1842
日久生厌
日久生厌 2021-01-04 23:00

My computer graphics homework is to implement OpenGL algorithms using only the ability to draw points.

So obviously I need to get drawLine() to work bef

3条回答
  •  粉色の甜心
    2021-01-04 23:23

    You can find the complete code in C++ to draw a line using Bresenham Algorithm at http://www.etechplanet.com/codesnippets/computer-graphics-draw-a-line-using-bresenham-algorithm.aspx:

    /*BRESENHAAM ALGORITHM FOR LINE DRAWING*/
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    void bhm_line(int,int,int,int,int);
    void main()
    {
     int ghdriver=DETECT,ghmode,errorcode,x1,x2,y1,y2;
     initgraph(&ghdriver,&ghmode,"..\\bgi");
     errorcode = graphresult();
     if(errorcode !=grOk)
     {
      cout<<"Graphics error:%s\n"<>x1>>y1;
     cout<<"Enter the coordinates (x2,y2): ";
     cin>>x2>>y2;
     bhm_line(x1,y1,x2,y2,1);
     getch();
    }
    void bhm_line(int x1,int y1,int x2,int y2,int c)
    {
     int x,y,dx,dy,dx1,dy1,px,py,xe,ye,i;
     dx=x2-x1;
     dy=y2-y1;
     dx1=fabs(dx);
     dy1=fabs(dy);
     px=2*dy1-dx1;
     py=2*dx1-dy1;
     if(dy1<=dx1)
     {
      if(dx>=0)
      {
       x=x1;
       y=y1;
       xe=x2;
      }
      else
      {
       x=x2;
       y=y2;
       xe=x1;
      }
      putpixel(x,y,c);
      for(i=0;x0 && dy>0))
        {
         y=y+1;
        }
        else
        {
         y=y-1;
        }
        px=px+2*(dy1-dx1);
       }
       delay(0);
       putpixel(x,y,c);
      }
     }
     else
     {
      if(dy>=0)
      {
       x=x1;
       y=y1;
       ye=y2;
      }
      else
      {
       x=x2;
       y=y2;
       ye=y1;
      }
      putpixel(x,y,c);
      for(i=0;y0 && dy>0))
        {
         x=x+1;
        }
        else
        {
         x=x-1;
        }
        py=py+2*(dx1-dy1);
       }
       delay(0);
       putpixel(x,y,c);
      }
     }
    }
    

提交回复
热议问题