2

我目前正在使用 Python 图形。(这和“Python Turtle”不一样,你可以通过谷歌搜索“Python Graphics”下载站点包。)搜索了一段时间关于如何绘制星星,我找不到任何关于这个的信息.

这是我弄清楚它是如何工作的唯一方法:

from graphics import *

def main():
    win = GraphWin('Star', 600, 600)
    win.setCoords(0.0, 0.0, 600.0, 600.0)
    win.setBackground('White')

    p1 = win.getMouse()
    p1.draw(win)
    p2 = win.getMouse()
    p2.draw(win)
    p3 = win.getMouse()
    p3.draw(win)
    p4 = win.getMouse()
    p4.draw(win)
    p5 = win.getMouse()
    p5.draw(win)
    p6 = win.getMouse()
    p6.draw(win)
    p7 = win.getMouse()
    p7.draw(win)
    p8 = win.getMouse()
    p8.draw(win)
    p9 = win.getMouse()
    p9.draw(win)
    p10 = win.getMouse()
    p10.draw(win)
    vertices = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10]
    print(vertices.getPoints())

    # Use Polygon object to draw the star
    star = Polygon(vertices)
    star.setFill('darkgreen')
    star.setOutline('darkgreen')
    star.setWidth(4)  # width of boundary line
    star.draw(win)

main()

这很有效,但效果不太好,因为我无法获得完美的星星,而且我总是不得不猜测我点击的位置。

4

1 回答 1

1

下面是一种基于在 C# 中绘制星形的代码来解决此问题的数学方法:

import math
from graphics import *

POINTS = 5
WIDTH, HEIGHT = 600, 600

def main():
    win = GraphWin('Star', WIDTH, HEIGHT)
    win.setCoords(-WIDTH/2, -HEIGHT/2, WIDTH/2, HEIGHT/2)
    win.setBackground('White')

    vertices = []

    length = min(WIDTH, HEIGHT) / 2

    theta = -math.pi / 2
    delta = 4 / POINTS * math.pi

    for _ in range(POINTS):
        vertices.append(Point(length * math.cos(theta), length * math.sin(theta)))
        theta += delta

    # Use Polygon object to draw the star
    star = Polygon(vertices)
    star.setFill('darkgreen')
    star.setOutline('lightgreen')
    star.setWidth(4)  # width of boundary line
    star.draw(win)

    win.getMouse()
    win.close()

main()

请注意,我更改了坐标系以简化解决方案。

此外,填充在某些系统(如 Unix)上可能看起来很奇怪(中间未填充),但在其他系统(如 Windows)上看起来完全填充。这是在支持 Zelle 图形的 Tkinter 库中实现填充的方式的产物:

在此处输入图像描述

您可以通过计算沿外周的点而不是仅仅计算恒星的(交叉)点来使其完全填充。

于 2017-01-08T07:56:56.063 回答