How to write bresenham algorithms in C #?

I wrote this, but it only works in 50% of cases. Can someone say what's wrong?

public void Bresenham(int x1,int y1,int x2,int y2,Color c)
        {            
            double dx = x2 - x1;
            double dy = y2 - y1;
            double d = 2*dy-dx; //aux variable
            double p1 = 2 * dy ;
            double p2 = 2 * (dy - dx);
            int x = x1;
            int y = y1;
            int xend;
            c = kolor;
            if (x1 > x2)
            {
                x = x2;
                y = y2;
                xend = x1;
            }
            else
            {
                x = x1;
                y = y1;
                xend = x2;
            }
            bitmapa.SetPixel(x, y,c);
            try
            {
                while (x < xend)
                {
                    x++;
                    if (d < 0)
                    {
                        d += p1;
                    }
                    else
                    {
                        d += p2;
                        y += 1;
                    }
                    bitmapa.SetPixel(x, y, c);
                }
            }

Thank:)

+3
source share
1 answer

At the first shot, you miss the case when you need to process a different coordinate, as you are now processing Y. Now you are processing the case when DY <DX, you must also handle the case when DX <DY, that is, the slope of the line is different.

To understand what I'm saying, look steep here .

And in fact, your algorithm will only work in 1/4 of the cases.

+4
source

Source: https://habr.com/ru/post/1796483/


All Articles