Question

Someone asked me how to write a function to draw a straight line between any two points. So I posted this question and answer to provide a solution for them.
I have paraphrased the user's question.

If I have two points:

(x1,y1) (x2,y2)

I can wrote the code to take an existing picture and create a new one. I know how to copy the picture. I can't figure out how to find the points on the line.

def straightLine(picture):
  height = getHeight(picture)
  width = getWidth(picture)
  newPicture = makeEmptyPicture(width, height)
  x1=//some value
  y1=//some value
  x2=//some value
  y2=//some value

  for y in range(0, height):
    for x in range(0, width):
      pxl = getPixel(picture,x,y)
      newPxl = getPixel(picture,x,y)
      color = getColor(pxl)
      setColor(newPxl,color)

  return picture
Was it helpful?

Solution

You need to use the following formula to find the line between two points.

(y-y0)/(y1-y0)=(x-x0)/(x1-x0)

In my code I have used x1,y1 and x2,y2 representative of the first and second points the user inputs.

Manipulate the above equation to solve for x as follows:

def drawAnyLine(p):
  w= getWidth(p)
  h= getHeight(p)
  newPic= makeEmptyPicture(w,h)
  x1=requestIntegerInRange("Enter x1 between 1 and " , 1,w)
  y1=requestIntegerInRange("Enter y1 between 1 and " , 1,h)
  x2=requestIntegerInRange ("Enter x2 between 1 and ", 1, w)
  y2=requestIntegerInRange("Enter y2 between 1 and ", 1, h)

  for y in range (y1,y2):
    for x in range (x1,x2):
      x = (y-y1)*(x2-x1)/(y2-y1) +x1
      pxl = getPixel(p, x, y)
      newPxl= getPixel(newPic,x,y)
      color = getColor(pxl)
      setColor ( newPxl, color)
  return (newPic)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top