Skip to content
Advertisement

using PIL to draw equal lines

what I’m trying to do is to draw horizontal lines in PIL of equal size. but my problem is that when I’m trying to fill the image it isn’t full. This is what I’m getting when it should be fully equal. There shouldn’t be any white. It also should work with more or less colors

Code

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)]

n = 0
length = len(colors)
amount = 1000 / length
x1 = 0
y1 = 0
x2 = 1000
y2 = 0
for color in colors:
    shape = [(x1, y1), x2, y2]
    draw.line(shape, fill=color, width=int(amount))
    y1 += amount
    y2 += amount

im.save('rect.png')

enter image description here

Advertisement

Answer

When drawing the line, you are specifying the center of the line, so your “shape” should be:

shape = [(x1, y1 + amount // 2), (x2, y2 + amount // 2)]

enter image description here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement