How to fix this Bresenham code drawing only in one direction

30 views Asked by At

I am trying to use the Bresenham algorithm to draw a line, but I can only draw the one in one direction, which I am assuming is the positive direction. After a few attempts, the program crashes. Here is the method for the algorithm:

public static void myLineBresenham(int x0, int y0,int x1,int y1,Bitmap bitmap,PictureBox pictureBox,Color color) {
    int width=bitmap.Width-1, height=bitmap.Height-1;
    int xi = x0;
    int yi = y0;
    int dx = x1 - x0,dy=y1-y0;

    if ((x1-x0)>(y1-y0)) {
        int p = 2 * dy - dx;
        while (xi <= x1)
        {
            if ((xi > 1) && (xi < width) && (yi > 1) && (yi < height))
            {
                bitmap.SetPixel(xi, yi, color);
                xi++;
            }
            if (p < 0)
            {
                p = p + 2 * dy;
            }
            else
            {
                p = p + 2 * dy - 2 * dx;
                yi++;
            }
        }
    }
    else {
        int p2 = 2 * dx - dy;
        while (yi<=y1) 
        {
            if ((xi > 1) && (xi < width) && (yi > 1) && (yi < height))
            {
                bitmap.SetPixel(xi, yi, color);
                xi++;
            }
            if (p2 < 0)
            {
                p2 =p2+2 * dx;
            }
            else
            {
                p2 =p2+2 * dx - 2 * dx;
                xi++;
            }
        }
    }
    pictureBox.Image= bitmap;
}

Output of the algorithm. After 3 attempts before program crashes

I did not know what to add to improve the code

0

There are 0 answers