欢迎访问宙启技术站
智能推送

利用Python随机生成FontProperties的字体颜色

发布时间:2023-12-10 23:17:08

import random

import matplotlib.pyplot as plt

from matplotlib.font_manager import FontProperties

# 字体列表

fonts = ['SimSun', 'SimHei', 'KaiTi', 'FangSong', 'Arial', 'Times New Roman']

# 随机生成1000个字体颜色及字体类型

colors = []

font_properties = []

for _ in range(1000):

    # 随机生成颜色

    r = random.random()

    g = random.random()

    b = random.random()

    color = (r, g, b)

    colors.append(color)

    

    # 随机选择字体类型

    font = random.choice(fonts)

    font_properties.append(FontProperties(fname=f'path_to_fonts/{font}.ttf'))

# 绘制示例文本

text = "Hello, world!"

fig, ax = plt.subplots()

for i in range(1000):

    ax.text(i % 10, i // 10, text, color=colors[i], fontproperties=font_properties[i])

plt.axis('off')

plt.show()