Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance: Add backup fonts support for dynamic generator #15

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions starbot/painter/DynamicPicGenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from PIL import Image, ImageDraw, ImageFont
from PIL.Image import Resampling
from fontTools.ttLib import TTFont
from emoji import is_emoji

from .PicGenerator import Color, PicGenerator
Expand Down Expand Up @@ -292,7 +293,10 @@ async def __get_content_line_imgs(cls, modules: List[Dict[str, Any]], width: int
img = Image.new("RGBA", (width, line_height))
draw = ImageDraw.Draw(img)
normal_font = config.get("PAINTER_NORMAL_FONT")
font = ImageFont.truetype(f"{cls.__resource_base_path}/resource/{normal_font}", 30)
if type(normal_font) == str:
normal_font = [normal_font]
draw_font_list = [ImageFont.truetype(f"{cls.__resource_base_path}/resource/{font}", 30) for font in normal_font]
judge_font_list = [TTFont(f"{cls.__resource_base_path}/resource/{font}", fontNumber=0) for font in normal_font]
emoji_font = ImageFont.truetype(f"{cls.__resource_base_path}/resource/emoji.ttf", 109)
x, y = 0, 0

Expand Down Expand Up @@ -337,6 +341,22 @@ def draw_pic(pic: Image, size: Optional[Tuple[int, int]] = None):
pic.close()
x = int(x + size[0])

def select_font_for_char(c: str) -> bool:
"""
选择字体

Args:
c: 字符

Returns:
包含该字符的字体或列表中最后一个字体
"""
for i in range(len(judge_font_list)):
for table in judge_font_list[i]['cmap'].tables:
if ord(c) in table.cmap.keys():
return draw_font_list[i]
return draw_font_list[-1]

def draw_char(c: str, color: Union[Color, Tuple[int, int, int]] = Color.BLACK):
"""
绘制字符
Expand All @@ -360,9 +380,10 @@ def draw_char(c: str, color: Union[Color, Tuple[int, int, int]] = Color.BLACK):
emoji_img = emoji_img.resize((30, 30), Resampling.LANCZOS)
draw_pic(emoji_img)
else:
text_width = draw.textlength(c, font)
draw_font = select_font_for_char(c)
text_width = draw.textlength(c, draw_font)
auto_next_line(text_width)
draw.text((x, y), c, color, font)
draw.text((x, y), c, color, draw_font)
x = int(x + text_width)

for module in modules:
Expand Down