函数在c中画一条直线

时间:2016-03-13 13:32:06

标签: c

我尝试创建一个函数来绘制一条直线,通过读取用户的两个点(x1,y1)开始行,(x2,y2)结束。 这是我的职责:

    void line(struct pixels* screen)
    {
       float X, Y;
       int i, j, x1, y1, x2, y2, mX, mY;
       scanf("%d%d%d%d", &x1, &y1, &x2, &y2);

       if ((x1 >= 0 && x1 <= screen->width) && (y1 >= 0 && y1 <= screen->height) && (x2 >= 0 && x2 <= screen->width) && (y2 >= 0 && y2 <= screen->height))
      {
         X = (x2 - x1);
         Y = (y2 - y1);
        if (X < 0)
            mX = X*(-1);
        else
            mX = X;

        if (Y < 0)
            mY = Y*(-1);
        else
            mY = Y;

        if( mX>mY )
        {
           if (X > 0)
           {
              for (i = 0; i < X; i++)
              {
                j = (int)(((i*Y) / X) + 0.5);
                screen->pixel[x1 + i][y1 + j] = '*';
              }

            }
            else
           {
             for (i = 0; i > X; i--)
             {
                j = (int)(((i*Y) / X) + 0.5);
                screen->pixel[x1 + i][y1 + j] = '*';
             }
            }

         }
        else
       {
          if (Y > 0)
          {
             for (j = 0; j < Y; j++)
             {
                i = (int)(((j*X) / Y) + 0.5);
                screen->pixel[x1 + i][y1 + j] = '*';
              }
           }
          else
          {
              for (j = 0; j > Y; j--)
              {
                 i = (int)(((j*X) / Y) + 0.5);
                 screen->pixel[x1 + i][y1 + j] = '*';
               }
           }
       }
   }
   else
       printf("ERROR: coordinates exceed the screen limits\n");
  }

问题是:当用户输入例如从(1,1)到(10,10)的行时,代码完美地工作,但是当它从(10,10)到(1,1)时它没有用!

1 个答案:

答案 0 :(得分:1)

谷歌Bresenham的线条绘制算法。在How OpenGL works: software renderer in 500 lines of code有关于如何处理此类事情的精彩教程/解释。您的具体问题在文章中提出。强烈推荐。

这是他的C ++实现:

void line(int x0, int y0, int x1, int y1, TGAImage &image, TGAColor color) { 
    bool steep = false; 
    if (std::abs(x0-x1)<std::abs(y0-y1)) { 
        std::swap(x0, y0); 
        std::swap(x1, y1); 
        steep = true; 
    } 
    if (x0>x1) { 
        std::swap(x0, x1); 
        std::swap(y0, y1); 
    } 
    int dx = x1-x0; 
    int dy = y1-y0; 
    float derror = std::abs(dy/float(dx)); 
    float error = 0; 
    int y = y0; 
    for (int x=x0; x<=x1; x++) { 
        if (steep) { 
            image.set(y, x, color); 
        } else { 
            image.set(x, y, color); 
        } 
        error += derror; 
        if (error>.5) { 
            y += (y1>y0?1:-1); 
            error -= 1.; 
        } 
    } 
}