I'm using Python PIL module to draw some lines and I use for loop to change the width of the line. But now I would like to do, when line width is to 0
, I want to go and add value of lw
. Basicly when width value go to zero, then I want it to go back to the 120.
This is my code...
from PIL import Image, ImageDraw
img = Image.new('RGB', (2000, 2000), (0, 0, 0))
draw = ImageDraw.Draw(img)
lw = 0
for y in range(-100, 2100, 100):
lw = lw 10
draw.line((2000, y, 0, y), (255,0,0), 120-lw)
img
This is an image from this code...
I was thinking to use if
statement but I don't know where to incorporate it. Any ideas?
Thanks in advance!
CodePudding user response:
for y in range(-100, 2100, 100):
lw = lw 10
draw.line((2000, y, 0, y), (255,0,0), 120-lw)
Nice attempt.
I was thinking to use
if
statement but I don't know where to incorporate it. Any ideas?
In this case I would suggest to do this:
for y in range(-100, 2100, 100):
lw = lw 10
if (lw >= 120): # When lw reaches 120...
lw = 0 # ...you set it to 0
draw.line((2000, y, 0, y), (255,0,0), 120-lw)
Anyway a more elegant solution (which doesn't involve if
statements) would be this:
for y in range(-100, 2100, 100):
lw = lw 10
draw.line((2000, y, 0, y), (255,0,0), 120-(lw0))
The %
operator gets the remainder of lw/120
, so that when lw>=120
you won't have a value greater than 120
anyway.
EDIT
I want to go from 120 to 0, and from 0 to 120. In this way it goes like this (120, 110,..., 20, 10, 0, 120, 110,...), but I would like to go like this (120, 110,..., 20, 10, 0, 10, 20,...,
In this case you have to use an if
statement:
incrementing = True
lw = 0
for y in range(-100, 2100, 100):
if (lw == 120):
incrementing = False
elif (lw == 0):
incrementing = True
if (incrementing):
lw = lw 10
else:
lw = lw - 10
draw.line((2000, y, 0, y), (255,0,0), 120-lw)
My suggestion is to use a bool
ean variable to make the incrementing/decrementing easier.