Algorithm for drawing a 4-connected line

后端 未结 2 1743
臣服心动
臣服心动 2020-12-05 20:40

I\'m looking for an algorithm (coded in Java would be nice, but anything clear enough to translate to Java is fine) to draw a 4-connected line. It seems that Bresenham\'s al

2条回答
  •  一个人的身影
    2020-12-05 20:57

    For the Python-illiterate, here is a C version of 6502's code:

    void drawLine(int x0, int y0, int x1, int y1) {
        int dx = abs(x1 - x0);
        int dy = abs(y1 - y0);
        int sgnX = x0 < x1 ? 1 : -1;
        int sgnY = y0 < y1 ? 1 : -1;
        int e = 0;
        for (int i=0; i < dx+dy; i++) {
            drawPixel(x0, y0);
            int e1 = e + dy;
            int e2 = e - dx;
            if (abs(e1) < abs(e2)) {
                x0 += sgnX;
                e = e1;
            } else {
                y0 += sgnY;
                e = e2;
            }
        }
    }
    

提交回复
热议问题