[英]How can draw a line using the x and y coordinates of two points?
I would like to know how to draw a line using the x and y coordinates of two 2-dimensional points.我想知道如何使用两个二维点的 x 和 y 坐标绘制一条线。 I tried the turtle graphics, but it works using degrees.
我尝试了海龟图形,但它使用度数工作。
Depending of your needs for plotting you can use matplotlib根据您的绘图需要,您可以使用matplotlib
import matplotlib.pyplot as plt
plt.plot([x1,x2],[y1,y2])
plt.show()
I tried the turtle graphics, but it works using degrees.
我尝试了海龟图形,但它使用度数工作。
Your premise doesn't hold -- turtle can do it, no degrees needed:你的前提不成立——乌龟可以做到,不需要学位:
import turtle
point1 = (50, 100)
point2 = (150, 200)
turtle.penup()
turtle.goto(point1)
turtle.pendown()
turtle.goto(point2)
turtle.hideturtle()
turtle.exitonclick()
You could make use of pygame depending on what you are doing it for as it allows a similar:您可以根据您的用途使用 pygame,因为它允许类似的:
line(Surface, color, (x1,y1), (x2,y2), width)
For Example, when the environment has been set up:例如,当环境已经设置好时:
pygame.draw.line(screen, (255,0,255), (20,20), (70,80), 2)
can draw:可以画:
If you are already using turtle
you can use a Tkinter
canva :如果您已经在使用
turtle
您可以使用Tkinter
画布:
import tkinter
x1, y1, x2, y2 = 10, 20, 30, 40
window = tkinter.Tk()
canva = tkinter.Canvas(window)
line = canva.create_line(x1, y1, x2, y2)
canva.pack()
You could calculate the angle from the 4 points using the following formula您可以使用以下公式从 4 个点计算角度
angle = arctan((y2-y1)/(x2-x1))
Just a warning, depending on the math library you use, this will probably output in radians.只是一个警告,根据您使用的数学库,这可能会以弧度输出。 However you can convert radians to degrees using the following formula.
但是,您可以使用以下公式将弧度转换为度数。
deg = rad * (180/pi)
Just for completeness, you can also use the ImageDraw module of Pillow (Python Image Library / PIL fork).为了完整起见,您还可以使用Pillow的ImageDraw 模块(Python Image Library / PIL fork)。 That way you don't need a window and you can save the drawn image into a file instead.
这样您就不需要窗口,而是可以将绘制的图像保存到文件中。
from PIL import Image, ImageDraw
im = Image.new('RGB', (100, 100))
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
im.save('test.png')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.