Last active
January 4, 2020 00:27
-
-
Save dimkouv/51cbf0882bbbc2c5b77ea9049cbc1b95 to your computer and use it in GitHub Desktop.
bresenham line algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"image" | |
"image/color" | |
"image/png" | |
"os" | |
) | |
func line(img *image.RGBA, x1, y1, x2, y2 int, color color.Color, mirror bool) { | |
dx, dy := x2-x1, y2-y1 | |
if dx < 0 { | |
dx = -dy | |
} | |
if dy < 0 { | |
dy = -dy | |
} | |
d := 2*dy - dx | |
incrE := 2 * dy | |
incrNE := 2 * (dy - dx) | |
for x, y := x1, y1; x <= x2; x++ { | |
if mirror { | |
img.Set(y, x, color) | |
} else { | |
img.Set(x, y, color) | |
} | |
if d <= 0 { | |
d += incrE | |
} else { | |
d += incrNE | |
if y1 < y2 { | |
y++ | |
} else if y1 > y2 { | |
y-- | |
} | |
} | |
} | |
} | |
func drawLine(img *image.RGBA, x1, y1, x2, y2 int, color color.Color) { | |
if x1 > x2 { | |
x1, x2 = x2, x1 | |
y1, y2 = y2, y1 | |
} | |
dx, dy := x2-x1, y2-y1 | |
if dy < 0 { | |
dy = -dy | |
} | |
if dy > dx { | |
line(img, y1, x1, y2, x2, color, true) | |
} else { | |
line(img, x1, y1, x2, y2, color, false) | |
} | |
} | |
func main() { | |
width := 1000 | |
height := 500 | |
density := 10 | |
blue := color.RGBA{0, 0, 255, 0xff} | |
red := color.RGBA{255, 0, 0, 0xff} | |
green := color.RGBA{0, 255, 0, 0xff} | |
black := color.RGBA{0, 0, 0, 0xff} | |
upLeft := image.Point{0, 0} | |
lowRight := image.Point{width, height} | |
img := image.NewRGBA(image.Rectangle{upLeft, lowRight}) | |
for i := 0; i < width; i++ { | |
for j := 0; j < height; j++ { | |
img.Set(i, j, black) | |
} | |
} | |
for i := 1000; i > 0; i -= density { | |
drawLine(img, width, 0, 0, i, red) | |
drawLine(img, 0, height, width, i, green) | |
drawLine(img, 0, 0, i, height, blue) | |
} | |
f, _ := os.Create("image.png") | |
_ = png.Encode(f, img) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment