Python Pillow - ImageDraw.rounded_rectangle() 函数



ImageDraw.rounded_rectangle() 方法用于绘制圆角矩形。矩形通过指定边界框、角的半径以及可选的填充颜色、轮廓颜色、线宽和每个角的圆角信息来定义。

语法

以下是函数的语法:

ImageDraw.rounded_rectangle(xy, radius=0, fill=None, outline=None, width=1, corners=None)

参数

以下是此函数参数的详细信息:

  • xy - 它指定定义圆角矩形边界框的两个点。可以将其指定为两个元组的序列 [(x0, y0), (x1, y1)] 或作为扁平列表 [x0, y0, x1, y1]。在这两种情况下,都必须满足条件 x1 >= x0 和 y1 >= y0。边界框包含两个端点。

  • radius - 圆角矩形的角半径。

  • fill - 用于填充圆角矩形的颜色。

  • outline - 用于圆角矩形轮廓的颜色。

  • width - 圆角矩形轮廓的线宽(以像素为单位)。默认值为 1。

  • corners - 一个元组,指示是否要圆角。元组格式为 (左上,右上,右下,左下)。此参数是关键字参数。

示例

示例 1

以下示例在指定的边界框内绘制一个带有圆角的圆角矩形,使用默认参数。

from PIL import Image, ImageDraw

# Create a new image with a white background
image = Image.new("RGB", (700, 300), "black")
draw = ImageDraw.Draw(image)

# Define the bounding box as a sequence of two tuples
bounding_box = [(250, 30), (450, 270)]

# Specify the radius for the rounded corners
radius = 20

# Draw a rounded rectangle default parameters
draw.rounded_rectangle(bounding_box, radius=radius)

# Display the image
image.show()
print('The rounded rectangle is drawn successfully...')

输出

The rounded rectangle is drawn successfully...

输出图像

rounded rectangle

示例 2

此示例在指定的边界框内绘制一个带有圆角的圆角矩形,填充为浅蓝色,轮廓为中等青绿色,并指定角的半径。

from PIL import Image, ImageDraw

# Create a new image with a white background
image = Image.new("RGB", (700, 300), "white")
draw = ImageDraw.Draw(image)

# Define the bounding box as a sequence of two tuples
bounding_box = [(250, 30), (450, 270)]

# Specify the radius for the rounded corners
radius = 50

# Specify fill and outline colors
fill_color = "lightblue"
outline_color = "mediumspringgreen"

# Draw a rounded rectangle
draw.rounded_rectangle(bounding_box, radius=radius, fill=fill_color, outline=outline_color, width=4)

# Display the image
image.show()
print('The rounded rectangle is drawn successfully...')

输出

The rounded rectangle is drawn successfully...

输出图像

rounded rectangle drawn

示例 3

以下示例演示如何在现有图像上使用不同的参数绘制圆角矩形。

from PIL import Image, ImageDraw

# Open an Image
image = Image.open('Images/TP-W.jpg')

# Create the draw object
draw = ImageDraw.Draw(image)

# Define the bounding box as a sequence of two tuples
bounding_box = [(245, 45), (445, 345)]

# Specify the radius for the rounded corners
radius = 40

# Draw a rounded rectangle with custom fill and outline colors
draw.rounded_rectangle(bounding_box, radius=radius, outline="red", width=4)

# Display the image
image.show()

print('The rounded rectangle is drawn successfully...')

输出

The rounded rectangle is drawn successfully...

输出图像

rounded rectangle custom fill
python_pillow_function_reference.htm
广告