【问题标题】:turtle drawing automatic centering乌龟绘图自动居中
【发布时间】:2016-11-02 12:24:36
【问题描述】:

我正在寻找自动查找新海龟绘图的起始位置的最佳方法,以便无论其大小和形状如何,它都会在图形窗口中居中。

到目前为止,我已经开发了一个函数,它检查每个绘制的元素海龟的位置,以找到左、右、上和下的极值,这样我就可以找到图片大小,并可以在发布我的代码之前使用它来调整起始位置.这是添加了我的图片大小检测的简单形状绘制示例:

from turtle import *

Lt=0
Rt=0
Top=0
Bottom=0

def chkPosition():
    global Lt
    global Rt
    global Top
    global Bottom

    pos = position()
    if(Lt>pos[0]):
        Lt = pos[0]
    if(Rt<pos[0]):
        Rt= pos[0]
    if(Top<pos[1]):
        Top = pos[1]
    if(Bottom>pos[1]):
        Bottom = pos[1]

def drawShape(len,angles):
    for i in range(angles):
        chkPosition()
        forward(len)
        left(360/angles)


drawShape(80,12)
print(Lt,Rt,Top,Bottom)
print(Rt-Lt,Top-Bottom)

这种方法确实有效,但是对我来说似乎很笨拙,所以我想请教更多经验的海龟程序员,有没有更好的方法来找到海龟绘图的起始位置以使其居中?

问候

【问题讨论】:

  • 使用几何寻找起始位置。

标签: python turtle-graphics


【解决方案1】:

没有一种通用的方法可以使每个形状居中(在绘制它并找到所有最大、最小点之前)。

对于您的形状(“几乎”圆形),您可以使用几何计算起点。

alpha + alpha + 360/repeat = 180 

所以

alpha = (180 - 360/repeat)/2

但我需要180-alpha 向右移动(然后向左移动)

beta = 180 - aplha = 180 - (180 - 360/repeat)/2

现在width

cos(alpha) = (lengt/2) / width

所以

width = (lengt/2) / cos(alpha)

因为Python在cos()中使用radians所以我需要

width = (length/2) / math.cos(math.radians(alpha))

现在我有了betawidth,所以我可以移动起点并且形状会居中。

from turtle import *
import math

# --- functions ---

def draw_shape(length, repeat):

    angle = 360/repeat

    # move start point

    alpha = (180-angle)/2
    beta = 180 - alpha

    width = (length/2) / math.cos(math.radians(alpha))

    #color('red')
    penup()

    right(beta)
    forward(width)
    left(beta)

    pendown()
    #color('black')

    # draw "almost" circle

    for i in range(repeat):
        forward(length)
        left(angle)

# --- main ---

draw_shape(80, 12)

penup()
goto(0,0)
pendown()

draw_shape(50, 36)

penup()
goto(0,0)
pendown()

draw_shape(70, 5)

penup()
goto(0,0)
pendown()

exitonclick()

我在图片上留下了红色的width

【讨论】:

    【解决方案2】:

    我很欣赏@furas 的解释和代码,但我避免使用数学。为了说明解决问题总是有另一种方法,这里有一个无需数学的解决方案,它产生相同的同心多边形:

    from turtle import Turtle, Screen
    
    def draw_shape(turtle, radius, sides):
    
        # move start point
    
        turtle.penup()
    
        turtle.sety(-radius)
    
        turtle.pendown()
    
        # draw "almost" circle
    
        turtle.circle(radius, steps=sides)
    
    turtle = Turtle()
    
    shapes = [(155, 12), (275, 36), (50, 5)]
    
    for shape in shapes:
        draw_shape(turtle, *shape)
        turtle.penup()
        turtle.home()
        turtle.pendown()
    
    screen = Screen()
    screen.exitonclick()
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      相关资源
      最近更新 更多