# -*- coding: utf-8 -*- # @File : 010_指定角星形.py # @Author : len # @Time : 2024/1/9 9:51 import matplotlib.pyplot as plt import numpy as np # 绘制填充的角星函数 def draw_filled_star(ax, center, size, color, points): """ 在给定的轴上绘制一个填充的角星。 center: 星星的中心 (x, y) 坐标。 size: 星星的大小。 color: 填充颜色。 points: 星星的角数。 """ # 计算所有顶点的角度和坐标 angles = np.linspace(0, 2 * np.pi, 2 * points + 1)[:2 * points] vertices = np.array([(np.cos(angle), np.sin(angle)) for angle in angles]) # 计算外部和内部顶点 outer_vertices = vertices[::2] * size + np.array(center) inner_vertices = vertices[1::2] * size / 2 + np.array(center) # 合并顶点列表,形成星星的路径 star_path = [outer_vertices[i//2] if i % 2 == 0 else inner_vertices[i//2] for i in range(2 * points)] # 绘制并填充星星 ax.fill(*zip(*star_path), color=color) # 设置绘图 fig, ax = plt.subplots() # 用户输入角星的角数 points = 6 # 示例:六角星 # 调整图形大小以适应星形 fig.set_size_inches(3, 3) # 绘制填充的角星 draw_filled_star(ax, center=(0, 0), size=1, color='green', points=points) # 移除坐标轴 ax.axis('off') # 保存具有透明背景的图像 plt.savefig('optimized_filled_star.png', transparent=True, format='png', dpi=300, bbox_inches='tight') plt.show() plt.close(fig) # 关闭图形,释放资源