Mashu
Mashu

Reputation: 29

drawing vertical and diagonal lines in PIL

im trying to generate are some equal vertical and diagonal lines in PIL. I already have horizontal lines but i cant get vertical and diagonal. enter image description here

Code for horizontal

from PIL import Image, ImageDraw
import random

im = Image.new('RGB', (1000, 1000), (255, 255, 255))
draw = ImageDraw.Draw(im)
colors = [(255,0,0), (255,255,0), (255,0,255)]
random.shuffle(colors)
n = 0
length = len(colors)
amount = 1000 / length
x1 = 0
y1 = 0
x2 = 0
y2 = 1000
for color in colors:
    shape = [(x1+ amount, y1  // 2), (x2+ amount, y2  // 2)]
    draw.line(shape, fill=color, width=int(amount))
    x1 += amount
    x2 += amount

im.save('rect.png')

Upvotes: 0

Views: 1002

Answers (2)

Mashu
Mashu

Reputation: 29

I got it! I just rotated my horizontal image:

colorimage = Image.open('horizontal.png')
out = colorimage.rotate(90)
out.save('vertical.png')

Upvotes: 0

martineau
martineau

Reputation: 123473

To draw the vertical lines filling the image, you need to position the endpoints of one line once for each of the color it will be drawn in. The initial X position of start and end points of the first line is ½ the line's width to the right of origin in the upper left of the image. The Y coordinates are 0 and image's height.

Code that does this:

from PIL import Image, ImageDraw
import random

IMG_WIDTH, IMG_HEIGHT = 1000, 1000

img = Image.new('RGB', (IMG_WIDTH, IMG_HEIGHT), (255, 255, 255))
draw = ImageDraw.Draw(img)
colors = [(255,0,0), (255,255,0), (255,0,255)]
random.shuffle(colors)

length = len(colors)
amount = IMG_WIDTH / length
offset = amount / 2  # 1/2 line width
x1, y1 = offset, 0
x2, y2 = offset, IMG_HEIGHT

for color in colors:
    endpoints = (x1, y1), (x2, y2)
    draw.line(endpoints, fill=color, width=int(amount))
    x1 += amount
    x2 += amount

img.save('rect.png')
#img.show()

Result:

screenshot

Upvotes: 2

Related Questions