Embedded_game/模块一/画图/009_爱心.py
2025-01-02 12:48:11 +08:00

50 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding:utf-8 -*-
# @Author len
# @Create 2023/12/31 16:44
import matplotlib.pyplot as plt
import numpy as np
def draw_heart(color='red', save_path='heart.png'):
"""
绘制一个爱心并保存为PNG文件。
参数:
color (str): 爱心的颜色,默认为红色。
save_path (str): 图像保存的路径。
"""
# 创建一个新的图形和轴,设置背景为透明
fig, ax = plt.subplots(figsize=(6, 5), dpi=100)
fig.patch.set_alpha(0.0)
# 定义心形曲线的参数方程
t = np.linspace(0, 2 * np.pi, 500) # 减少采样点数量以提高性能
x = 16 * np.sin(t)**3
y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)
# 缩放和平移心形曲线以适应绘图区域
x = 0.5 * x / 16 + 0.5
y = -0.5 * y / 13 + 0.75
# 绘制心形,颜色为指定颜色
ax.fill(x, y, color=color)
# 设置坐标轴的范围
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
# 移除坐标轴
ax.axis('off')
# 保存图像为PNG格式背景设为透明
plt.savefig(save_path, transparent=True, bbox_inches='tight', pad_inches=0)
# 关闭图形,避免显示
plt.close()
# 调用函数绘制红色爱心,并指定保存路径
draw_heart(color='red', save_path='optimized_heart.png')