Reputation:
I am trying to draw parallel lines diagonally from the top right corner to the bottom left corner of a picture. I want it to look like this (lovely paint pic)
def diagTopLBottomR():
pic=makePicture(pickAFile())
w=getWidth(pic)
h=getHeight(pic)
x1=0
y1=0
x2=0
y2=0
i=0
while i<11:
x1=10*i
y2=10*i
i+=1
for y in range (y1,y2):
x = (y-y1)*(x2-x1)/(y2-y1) +x1
px=getPixel(pic,x,y)
color=makeColor(0,0,0)
setColor(px, color)
x3=0
y3=h
x4=w
y4=0
j=0
while j<10:
x3=10*j
y4=10*j
j+=1
for y in range (y3,y4):
x = (y-y3)*(x4-x3)/(y4-y3) +x3
px=getPixel(pic,x,y)
color=makeColor(0,0,0)
setColor(px, color)
return(pic)
You'll note that the x3 will either be max value, causing an outof range exception, or the y range will start with a higher value ie (y3>y4) and doesn't work in reverse, or when I decrement it. It's like a paradox.
The first loop is working, no matter what I try I cannot get the second loop to work. This is what I'm ending up with.
Any ideas? Thanks.
Edit
I have played around with the ranges, and either get no result for the second loop, as shown above of an out of range exception.
I have tried:
x3=0
y3=h
x4=w
y4=0
j=0
while j<10:
x3=10*j
y4=10*j
j+=1
for x in range (x3,x4):
y = (x-x3)*(y4-y3)/(x4-x3) +y3
Stole Unicorns from here.
Upvotes: 6
Views: 2203
Reputation:
I solved it by making px=getPixel(pic,x,y-1)
and using the suggested answers of decrementing y range.
def diagTopLBottomR():
pic=makePicture(pickAFile())
w=getWidth(pic)
h=getHeight(pic)
x1=0
y1=0
x2=0
y2=0
i=0
while i<10:
x1=10*i
y2=10*i
i+=1
for y in range (y1,y2):
x = (y-y1)*(x2-x1)/(y2-y1) +x1
px=getPixel(pic,x,y)
color=makeColor(0,0,0)
setColor(px, color)
x3=0
y3=h
x4=w
y4=0
j=0
while j<10:
x3=10*j
y4=10*j
j+=1
for y in range (y3,y4,-1):#change here
x = abs((y-y3)*(x4-x3)/(y4-y3) +x3)
px=getPixel(pic,x,y-1)#change here
color=makeColor(0,0,0)
setColor(px, color)
return(pic)
Upvotes: 2
Reputation: 7799
In the second loop, y3
is greater (or equal) than y4
. So, try range (y4,y3)
.
Upvotes: 5
Reputation: 1557
In the first part, y1
is set to 0 and y2
increases from 0 in the loop, so y1 < y2
. This is fine because you use
for y in range (y1,y2)
In the second part, y3
is set to h
(128 in your case, I guess) and y4
increases from 0 in the loop, so y3 > y4
. This is NOT fine because you use
for y in range (y3,y4)
You could try stepping backwards by giving range()
a third parameter indicating a step size of -1. Or you could switch y3
and y4
(be cautious of what this does to the rest of your code).
Upvotes: 8
Reputation: 13158
range()
assumes the first parameter is less than the second parameter, and it goes in an ascending order. You have:
for y in range (y3,y4):
where y3=h
and y4=0
(on the first pass). Since y3 > y4, this loop does nothing.
You can use either:
for y in range(y4,y3):
or
for y in range(y3,y4,-1):
Upvotes: 5