问题
I'm trying to fill a line by a different color increasingly like a progress bar. This is the image:
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:
Should I just fill each line separately and combine them all?
回答1:
Interesting question! You could have lots of fun thinking up ways to do this.
- 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.
- 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.
- 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.
- 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.
来源:https://stackoverflow.com/questions/62671427/fill-pil-imagedraw-line-partially