简体   繁体   中英

How do I get the xy coordinates for drawing a line?

I want to get the coordinates that you should go to in order to draw a diagonal line. I imagine something like:

def drawLine(x,y,x1,y1):
    return #all the coordinates that you need to go to in order to draw from x y to x1 y1
def drawLine(x,y,x1,y1):
   if (x>x1):
      temp = x
      x = x1
      x1 = temp
   elif (y>y1):
       temp = y
       y = y1
       y1 = temp
          
   listx = list(i for i in range (x,x1+1))
   listy = list(j for j in range (y,y1+1))
    
   m = (y1-y)/(x1-x)
   c = y - (m*x)
       
   for i in listx:
      for j in listy:
         if((i*m)+c == j):
            print("(",str(i),",",str(j),")")
          
   drawLine(0,0,3,3)

This program works for integer co-ordinates. This is an implementation co-ordinate geometry theories, where m refers to gradient and c refers to the intercept. Float or double have infinite co-ordinates mathematically.

def drawLines(x1, y1, x2, y2):
    r = 10 # resolution
    diff_x, diff_y = abs(x2-x1),abs(y2-y1)
    return [(diff_x*i/r + x1 if x2>x1 else x1 - diff_x*i/r , diff_y*i/r + y1 if y2>y1 else y2-diff_y*i/r) for i in range(r+1)]

This code should be working. For example;

print(drawLines(3,1,1,3)) # Returns a list of points
# [(3.0, 1.0), (2.8, 1.2), (2.6, 1.4), (2.4, 1.6), (2.2, 1.8), (2.0, 2.0), (1.8, 2.2), (1.6, 2.4), (1.4, 2.6), (1.2, 2.8), (1.0, 3.0)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM