1

I am trying to draw a diagonal line between two (x,y) coordinates using the GoLang "image" package import.

From what I can tell, the package allows for drawing rectangles, and has objects for horizontal and vertical lines, as described in this article.

Draw a rectangle in Golang?

I see image.Rect() to create a rectangle, which is needed to input into the draw.Draw() function

I see HLine() and VLine() functions for vertical and horizontal lines, which are used for the rectangles in the image.Rect() function.

However, I cannot figure out how to draw a custom line between any two coordinates. I want to input an x1, y1, x2, y2 format.

I have tried to draw the points on a diagonal line one at a time as 2x2 rectangles, using the slope-intercept formula.

        for h := x1; h <= x2; h++ {
            // make each dot drawn 2x2 instead of 1x1
            // h is x coordinate of a pixel
            //"int(float64(branch.root.y)+(float64(h)*slope)" is the y coordinate using slope 
            // intercept formula
            currentDot := image.Rect(h, int(float64(branch.root.y)+(float64(h)*slope)),
                h+1, int(float64(branch.root.y)+(float64(h)*slope))+1)
            fmt.Println("point draw", h, int(float64(branch.root.y)+(float64(h)*slope)),
                h+1, int(float64(branch.root.y)+(float64(h)*slope))+1)
             
            // negative coordiantes don't allow it to be drawn
            //fmt.Println("dot drawn")
            draw.Draw(myImage, currentDot, &image.Uniform{white}, image.ZP, draw.Src)

However, it has given me trouble. Some of it is the math involved in coordinate calculation that I need to fix otherwise. But it would also be helpful to be able to draw diagonal lines from any two coordinates.

0 Answers0