From 4a6bbc4b1b53373d53547db74ea8f0413f37c8b8 Mon Sep 17 00:00:00 2001 From: cloudwish Date: Sat, 13 Jul 2024 00:12:44 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=BA=E5=8A=A8=E6=80=81=E7=BB=98=E5=88=B6?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=A4=87=E7=94=A8=E5=AD=97=E4=BD=93=E6=94=AF?= =?UTF-8?q?=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- starbot/painter/DynamicPicGenerator.py | 27 +++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/starbot/painter/DynamicPicGenerator.py b/starbot/painter/DynamicPicGenerator.py index 4c049f5..462b537 100644 --- a/starbot/painter/DynamicPicGenerator.py +++ b/starbot/painter/DynamicPicGenerator.py @@ -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 @@ -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 @@ -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): """ 绘制字符 @@ -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: