简体   繁体   中英

How to rezise image with x,y coordinates (turtle graphics)

I Have Created a Maple Leaf via turtle in python. I have found a way to translate the shape over the x and y axis but I haven't found a way to resize the maple leaf while keeping its original form.

import turtle
def MapleLeaf(x=None,y=None):
    if x==None:
        x=0
    if y==None:
        y=0
    turtle.penup()
    turtle.goto(1+x,-3+y)
    turtle.pendown()
    turtle.goto(5+x,-4+y)
    turtle.goto(4+x,-3+y)
    turtle.goto(9+x,1+y)
    turtle.goto(7+x,2+y)
    turtle.goto(8+x,5+y)
    turtle.goto(5+x,4+y)
    turtle.goto(5+x,5+y)
    turtle.goto(3+x,4+y)
    turtle.goto(4+x,9+y)
    turtle.goto(2+x,7+y)
    turtle.goto(0+x,10+y)
    turtle.goto(-2+x,7+y)
    turtle.goto(-4+x,8+y)
    turtle.goto(-3+x,3+y)
    turtle.goto(-5+x,6+y)
    turtle.goto(-5+x,4+y)
    turtle.goto(-8+x,5+y)
    turtle.goto(-7+x,2+y)
    turtle.goto(-9+x,1+y)
    turtle.goto(-4+x,-3+y)
    turtle.goto(-5+x,-4+y)
    turtle.goto(0+x,-3+y)
    turtle.goto(2+x,-7+y)
    turtle.goto(2+x,-6+y)
    turtle.goto(1+x,-3+y)
    turtle.hideturtle()

turtle.pencolor("black")
turtle.fillcolor("red")
turtle.begin_fill()
MapleLeaf(50,50)
turtle.end_fill()
turtle.done()

In order to change the scale of the figure you're drawing, multiply all of the offsets from your x and y positions by a scale factor:

def MapleLeaf(x=0, y=0, scale=1):
    turtle.penup()
    turtle.goto(1*scale+x,-3*scale+y)
    turtle.pendown()
    turtle.goto(5*scale+x,-4*scale+y)
    turtle.goto(4*scale+x,-3*scale+y)
    turtle.goto(9*scale+x,1*scale+y)
    # ...

Note that I got rid of your if statements at the start, since you can just use 0 as a default value. Its only with mutable default values (like lists) that you need to always use a sentinel like None to signal the default is wanted.

Since the scale and x and y offsets are repeated so much, you might want to factor them out further into a function:

def MapleLeaf(x=0, y=0, scale=1):
    def my_goto(x_offset, y_offset):
        turtle.goto(x + scale*x_offset, y + scale*y_offset)

    turtle.penup()
    my_goto(1, -3)
    turtle.pendown()
    my_goto(5, -4)
    my_goto(4, -3)
    my_goto(9, 1)
    # ...

Another alternative might be to put the offsets into a list, and iterate over them in a loop.

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