Bresenham lines w/o diagonal movement

后端 未结 3 993
遥遥无期
遥遥无期 2020-12-22 01:41

Is there a modified Bresenham algorithm, where the step from one pixel to the next one isn\'t allowed to be diagonally, just horizontally or vertically? Or any other algorit

3条回答
  •  囚心锁ツ
    2020-12-22 02:37

    I have found that Franz D's answer produces lines that do not closely match the original when close to the horizontal or vertical. While the function below is not perfect, I have found it produces nicer results.

    Function BresenhamLineNew : Void( x0 : Int, y0 : Int, x1 : Int, y1 : Int )
    
        Local dx : Int = Abs( x1 - x0 )
        Local dy : Int = Abs( y1 - y0 )
    
        Local sx : Int = -1
        Local sy : Int = -1
    
        If x0 < x1 Then sx = 1
        If y0 < y1 Then sy = 1
    
        Local err : Int = dx - dy
        Local e2 : Int
    
        While True
    
            DrawRect x0, y0, 1, 1
    
            If x0 = x1 And y0 = y1 Then Exit
    
            e2 = 2 * err
    
            If dy > dx
                If e2 > -dy
                    err = err - dy
                    x0 = x0 + sx
                Elseif e2 < dx
                    err = err + dx
                    y0 = y0 + sy
                Endif
            Else
                If e2 < dx
                    err = err + dx
                    y0 = y0 + sy
                Elseif e2 > -dy
                    err = err - dy
                    x0 = x0 + sx
                Endif
            Endif
    
        Wend
    
    End Function
    

提交回复
热议问题