运行代码
def draw_tian_zig(rows=1, cols=1, char_size=2):
"""
绘制字符田字格
:param rows: 行数,默认为1行
:param cols: 列数,默认为1列
:param char_size: 每个格子的字符大小,默认为2
:return: 生成的田字格字符串
"""
# 田字格的基本组成元素
top_border = '┌' + '─' * char_size + '┬' + '─' * char_size + '┐'
middle_border = '├' + '─' * char_size + '┼' + '─' * char_size + '┤'
bottom_border = '└' + '─' * char_size + '┴' + '─' * char_size + '┘'
content_line = '│' + ' ' * char_size + '│' + ' ' * char_size + '│'
# 如果需要多列,调整边框
if cols > 1:
top_border = '┌' + ('─' * char_size + '┬') * (cols * 2 - 1) + '─' * char_size + '┐'
middle_border = '├' + ('─' * char_size + '┼') * (cols * 2 - 1) + '─' * char_size + '┤'
bottom_border = '└' + ('─' * char_size + '┴') * (cols * 2 - 1) + '─' * char_size + '┘'
content_line = '│' + (' ' * char_size + '│') * (cols * 2)
elif cols == 1:
# 单个田字格已经处理好了
pass
# 拼接整个田字格
tian_ge = ''
tian_ge += top_border + '\n'
for r in range(rows):
# 每个汉字格占char_size行
for i in range(char_size):
tian_ge += content_line + '\n'
# 如果不是最后一行,添加中间分隔线
if r != rows - 1:
tian_ge += middle_border + '\n'
tian_ge += bottom_border
return tian_ge
def draw_character_grid(chars, cols_per_row=3, char_size=2):
"""
将给定字符绘制到田字格中
:param chars: 要绘制的字符列表或字符串
:param cols_per_row: 每行多少个字,默认为3个
:param char_size: 每个格子的大小,默认为2
:return: 生成的田字格字符串
"""
if isinstance(chars, str):
chars = list(chars)
# 计算需要多少行
total_chars = len(chars)
rows = (total_chars + cols_per_row - 1) // cols_per_row
# 创建格子
# 每个汉字占2格(田字格)
total_cols = cols_per_row
# 边框定义
cell_width = char_size
top_border = '┌' + ('─' * cell_width + '┬' + '─' * cell_width + '┼') * total_cols
top_border = top_border[:-1] + '┐'
middle_horizontal_border = '├' + ('─' * cell_width + '┼' + '─' * cell_width + '┼') * total_cols
middle_horizontal_border = middle_horizontal_border[:-1] + '┤'
bottom_border = '└' + ('─' * cell_width + '┴' + '─' * cell_width + '┴') * total_cols
bottom_border = bottom_border[:-1] + '┘'
# 构建结果
result = top_border + '\n'
for row in range(rows):
# 每个汉字需要char_size行内容
for line in range(char_size):
current_line = ''
# 处理这一行的每个汉字
for col in range(cols_per_row):
char_index = row * cols_per_row + col
char = chars[char_index] if char_index < len(chars) else ' '
# 田字格左半部分和右半部分
if line == char_size // 2:
# 中线位置,放置字符
left_part = ' ' * ((cell_width - 1) // 2) + char + ' ' * (cell_width - (cell_width - 1) // 2 - 1)
else:
left_part = ' ' * cell_width
right_part = ' ' * cell_width
current_line += f'│{left_part}│{right_part}'
current_line += '│\n'
result += current_line
# 如果不是最后一行,添加分隔线
if row != rows - 1:
result += middle_horizontal_border + '\n'
result += bottom_border
return result
from PIL import Image, ImageDraw, ImageFont
import os
def draw_character_grid_to_image(chars, cols_per_row=3, char_size=2, output_file='tian_zi_ge.png', font_size=24):
"""
将字符田字格渲染为图片
:param chars: 要绘制的字符列表或字符串
:param cols_per_row: 每行多少个字,默认为3个
:param char_size: 每个格子的大小,默认为2(对应终端中的大小)
:param output_file: 输出图片文件名
:param font_size: 字体大小
:return: 生成的图片文件路径
"""
# 获取文本格式的田字格
text_grid = draw_character_grid(chars, cols_per_row, char_size)
lines = text_grid.split('\n')
# 计算图片尺寸
line_width = max(len(line) for line in lines)
char_width = font_size // 2
image_width = line_width * char_width + 20 # 添加一些边距
image_height = len(lines) * (font_size // 2) + 20
# 创建图片
image = Image.new('RGB', (image_width, image_height), color='white')
draw = ImageDraw.Draw(image)
# 尝试加载字体,优先使用系统中文字体
font_paths = [
'C:/Windows/Fonts/msyh.ttc', # 微软雅黑
'C:/Windows/Fonts/simsun.ttc', # 宋体
'C:/Windows/Fonts/simhei.ttf', # 黑体
'/usr/share/fonts/truetype/wqy/wqy-microhei.ttc', # Linux 文泉驿微米黑
'/System/Library/Fonts/PingFang.ttc' # macOS 苹方
]
font = None
for font_path in font_paths:
if os.path.exists(font_path):
try:
font = ImageFont.truetype(font_path, font_size)
break
except Exception:
continue
if font is None:
font = ImageFont.load_default()
# 绘制每一行文字
y = 10
line_height = font_size // 2
for line in lines:
x = 10
for char in line:
draw.text((x, y), char, fill='black', font=font)
x += char_width
y += line_height
# 保存图片
image.save(output_file)
print(f"图片已保存到: {output_file}")
return output_file
if __name__ == '__main__':
print('=== 示例1:单个空白田字格 ===')
print(draw_tian_zig(1, 1, 2))
print()
print('=== 示例2:2行2列空白田字格 ===')
print(draw_tian_zig(2, 2, 2))
print()
print('=== 示例3:在田字格中写汉字 "中 国 人" ===')
result = draw_character_grid('中国人', cols_per_row=3, char_size=3)
print(result)
print()
print('=== 示例4:自定义字符串田字格 ===')
user_input = '你好世界'
print(f'绘制字符串 "{user_input}":')
result = draw_character_grid(user_input, cols_per_row=2, char_size=3)
print(result)
print()
print('=== 示例5:生成包含数字、字母和文字的田字格图片 ===')
mixed_chars = 'A1中b2文c3好'
output_path = 'c:/Users/Administrator/Desktop/1/tian_zi_ge_output.png'
draw_character_grid_to_image(mixed_chars, cols_per_row=4, char_size=4, output_file=output_path, font_size=32)
print(f"已生成包含数字、字母和文字的田字格图片: {output_path}")
运行截图
作业心得
该作业让我感受到字符田字格渲染成图片的便捷,而且对不同边框的处理也不同显得无比精细