Drawing diagonal lines on an image

user2194374 picture user2194374 · Mar 23, 2013 · Viewed 12.5k times · Source

Hi im trying to draw diagonal lines across an image top right to bottom left here is my code so far.

  width = getWidth(picture)
  height = getHeight(picture)
  for x in range(0, width):
    for y in range(0, height):
      pixel = getPixel(picture, x, y)
      setColor(pixel, black)

Thanks

Answer

MartinStettner picture MartinStettner · Mar 23, 2013

Most graphic libraries have some way to draw a line directly.

In JES there is the addLine function, so you could do

addLine(picture, 0, 0, width, height)

If you're stuck with setting single pixels, you should have a look at Bresenham Line Algorithm, which is one of the most efficient algorithms to draw lines.

A note to your code: What you're doing with two nested loops is the following

for each column in the picture
  for each row in the current column
     set the pixel in the current column and current row to black

so basically youre filling the entire image with black pixels.

EDIT

To draw multiple diagonal lines across the whole image (leaving a space between them), you could use the following loop

width = getWidth(picture)
height = getHeight(picture)
space = 10
for x in range(0, 2*width, space):
  addLine(picture, x, 0, x-width, height)

This gives you an image like (the example is hand-drawn ...)

diagonal lines

This makes use of the clipping functionality, most graphics libraries provide, i.e. parts of the line that are not within the image are simply ignored. Note that without 2*width (i.e. if x goes only up to with), only the upper left half of the lines would be drawn...