Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

algorithm - How to draw a line by pixels?

I've got some idea, but for example if the starting point is at {0; 0} and end point is {8; 13} then at the end there would be a straight line of ~5 pixels, if I'm not mistaken, has anyone got any better algorithm?

Here's my code:

func DrawLine(x1, y1, x2, y2 int, r, g, b uint8) {
    var Lcolor color.Color
    if x1 == x2 {
        for targY := y1; targY != y2; {
            surface.Set(x1, targY, Lcolor)
            if y1 < y2 {targY++} else {targY--}
        }
    } else if y1 == y2 {
        for targX := x1; targX < x2; targX++ {
            surface.Set(targX, y1, Lcolor)
        }
    } else {
        var diff [2]float64 = [2]float64{float64(x2 - x1), math.Abs(float64(y2) - float64(y2))}
        if y1 < y2 && diff[0] / diff[1] >= 1 {
            rate := int(math.Ceil(diff[0] / diff[1]))
            for targX, targY := x1, y1; targX < x2; targY++ {
                if y1 == y2 {for {if targX == x2 {return} else {surface.Set(targX, targY, Lcolor); targX++}}}
                for cnt := 0; cnt <= rate; cnt++ {
                    targX += cnt
                    surface.Set(targX, targY, Lcolor)
                }
            }
        } else if y1 < y2 && diff[0] / diff[1] < 1 {
            rate := int(math.Ceil(diff[1] / diff[0]))
            //Not finished yet
        } else if y1 > y2 && diff[0] / diff[1] >= 1 {
            rate := int(math.Ceil(diff[0] / diff[1]))
            //Not finished yet
        } else if y1 > y2 && diff[0] / diff[1] < 1 {
            rate := int(math.Ceil(diff[1] / diff[0]))
            //Not finished yet
        }
    }
}
question from:https://stackoverflow.com/questions/65875851/how-to-draw-a-line-by-pixels

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...