Python Pillow - ImageDraw.regular_polygon() 函数



ImageDraw.regular_polygon() 方法用于绘制一个内接于边界圆的正多边形。多边形通过指定边界圆、边数和可选的旋转来定义。

语法

以下是该函数的语法:

ImageDraw.regular_polygon(bounding_circle, n_sides, rotation=0, fill=None, outline=None, width=1)

参数

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

  • bounding_circle - 它是一个元组,定义了边界圆的中心点和半径。它可以指定为元组 (x, y, r) 或 ((x, y), r)。多边形内接于此圆。

  • n_sides - 它指定正多边形的边数(例如,n_sides=3 表示三角形,n_sides=6 表示六边形)。

  • rotation - 一个可选参数,以度数指定对多边形的任意旋转(例如,rotation=90 表示 90 度旋转)。默认为不旋转(rotation=0)。

  • fill - 用于填充多边形的颜色。

  • outline - 用于多边形轮廓的颜色。

  • width - 多边形轮廓的线宽,以像素为单位。默认值为 1。

示例

示例 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 circle as a tuple (center, radius)
bounding_circle = ((350, 150), 100)

# Specify the number of sides for the regular polygon
n_sides = 5

# Draw a regular polygon inscribed in the bounding circle
draw.regular_polygon(bounding_circle, n_sides)

# Display the image
image.show()

print('The regular polygon is drawn successfully...')

输出

The regular polygon is drawn successfully...

输出图像

regular polygon

示例 2

此示例绘制一个正五边形,该五边形内接于一个边界圆,并具有指定的中心和半径。填充颜色设置为中等春绿色,轮廓颜色设置为黄色,线宽为 5 个像素。

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 circle as a tuple (center, radius)
bounding_circle = ((350, 150), 100)

# Specify the number of sides for the regular polygon
n_sides = 6

# Draw a regular polygon inscribed in the bounding circle
draw.regular_polygon(bounding_circle, n_sides, fill='mediumspringgreen', outline='yellow', width=5)

# Display the image
image.show()

print('The regular polygon is drawn successfully...')

输出

The regular polygon is drawn successfully...

输出图像

green polygon

示例 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 circle as a tuple (center, radius)
bounding_circle = ((345, 145), 100)

# Specify the number of sides for the regular polygon
n_sides = 5

# Set fill and outline colors
fill_color = "red"
outline_color = "black"

# Draw a regular polygon inscribed in the bounding circle
draw.regular_polygon(bounding_circle, n_sides, fill=fill_color, outline=outline_color, width=4)

# Display the image
image.show()

print('The regular polygon is drawn successfully...')
The regular polygon is drawn successfully...

输出

The regular polygon is drawn successfully...

输出图像

red polygon
python_pillow_function_reference.htm
广告