Pillow is a package devoted to working with images in Python. Starting in Pillow 8.2, there is a new drawing type: the rounded rectangle. A rounded rectangle lets you round the corners of the rectangle. So instead of sharp corners, you get rounded ones! You can read all about the new drawing type in the Pillow documentation.
Make sure that you have the latest version of Pillow. If you have a version of Pillow older than 8.2, then you won't be able to use this new type of drawing.
Here is how you can upgrade Pillow:
python3 -m pip install pillow --upgrade
Now that you have Pillow installed or upgraded, you can use the new drawing type.
You are now ready to draw a rounded rectangle. Open up a new file in your favorite Python IDE and add the following code:
# draw_rounded_rectangle.py from PIL import Image, ImageDraw def rectangle(output_path): image = Image.new("RGB", (400, 400), "green") draw = ImageDraw.Draw(image) # Draw a regular rectangle draw.rectangle((200, 100, 300, 200), fill="red") # Draw a rounded rectangle draw.rounded_rectangle((50, 50, 150, 150), fill="blue", outline="yellow", width=3, radius=7) image.save(output_path) if __name__ == "__main__": rectangle("rounded_rectangle.jpg")
The rounded_rectangle() function takes in a tuple of four integers. These integers define the two points of the bounding box. The radius defines how much to round the corners. You can fill the rectangle with a color. You can also add a border using the outline parameter. The width is the number of pixels thick the border should be.
When you run this code, it will create an image that contains a regular rectangle and a rectangle with rounded corners that looks like this:
The blue rectangle on the left shows what a rounded rectangle looks like. If you set the radius to zero, then the corners are not rounded at all. The larger the radius value, the larger the curve on the corners.
While this new drawing type isn't amazing, it's a nice new tool to add to your drawing toolkit. If you are stuck using a version of Pillow older than 8.2, there are some alternate solutions for creating rounded rectangles on StackOverflow. Have fun!
Copyright © 2024 Mouse Vs Python | Powered by Pythonlibrary