Fill PIL ImageDraw Line partially

Viewed 192

I'm trying to fill a line by a different color increasingly like a progress bar. This is the image:

enter image description here

It was created with this code

from PIL import Image, ImageDraw

image = Image.new("RGBA", (300, 300), color="black")
draw = ImageDraw.Draw(image)
width = 7
image_w, image_h = image.size
coord_a = image_w / 2, width
coord_b = width, image_h / 2
coord_c = image_w / 2, image_h - width
coord_d = image_w - width, image_h / 2
draw.line([coord_a, coord_b, coord_c, coord_d, coord_a], fill="red", width=width, joint="curve")
image.show()
image.save("test.png")

I'm trying to fill it with different color like this:
enter image description here
Should I just fill each line separately and combine them all?

1 Answers

Interesting question! You could have lots of fun thinking up ways to do this.


  1. As you suggest, you could draw the rhombus as four separate lines. You would have to calculate the point where the red and blue portion met using sin/cos but that's not too hard.

  1. You could draw it much more simply as the four sides of a square with its sides initially horizontal and vertical, then rotate it 45 degrees into place when you are finished drawing. I think I would go for this option.

  1. You could draw a single long horizontal red line, and then overdraw the correct percentage in blue. Then cut it into four pieces, rotate and paste onto the black square background.

  1. You could get the coordinates of all the points on the rhombus using scikit-image draw.polygon_perimeter() as documented here. Then colour the first however many percent blue and the remainder in red. You could make the lines thicker using morphological dilation.
Related