#!/usr/bin/env python3 """生成 PWA 图标(``public/icons/*.png``)。 为什么要一个脚本而不是把图扔进仓库就完事:图标是**跟着主题色走的**—— 底色就是 tailwind.config.js 里 primary 那一档(#14b8a6 → #0f766e, 与应用里那块 "OA" 磁贴同一支渐变),字形沿用侧边栏上用户已经认了很久的两个字母。 哪天改主色或改字形,跑一次这 script 就整套对齐,不用一张一张 P。 只在改图标时跑一次,需要 Pillow(不装进 package.json,构建流程不碰它):: python3 scripts/gen-icons.py """ from __future__ import annotations from pathlib import Path from PIL import Image, ImageDraw, ImageFont OUT_DIR = Path(__file__).resolve().parent.parent / "public" / "icons" #: 与 tailwind.config.js 的 primary-500 / primary-700 对齐(同一支 gradient-primary) TOP = (20, 184, 166) BOTTOM = (15, 118, 110) TEXT = (255, 255, 255) WORD = "OA" #: macOS 自带的粗体无衬线;找不到就退回 PIL 自带的位图字体(会被放大,仅兜底) FONT_CANDIDATES = ( "/System/Library/Fonts/Supplemental/Arial Bold.ttf", "/Library/Fonts/Arial Bold.ttf", "C:\\Windows\\Fonts\\arialbd.ttf", ) def font(size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont: for path in FONT_CANDIDATES: if Path(path).exists(): return ImageFont.truetype(path, size) return ImageFont.load_default() def gradient(size: int) -> Image.Image: """左上到右下的线性渐变,跟 CSS 的 135deg 同一走向。""" img = Image.new("RGB", (size, size), TOP) pixels = img.load() for y in range(size): for x in range(size): ratio = (x / size + y / size) / 2 pixels[x, y] = tuple( round(TOP[i] + (BOTTOM[i] - TOP[i]) * ratio) for i in range(3) ) return img def draw_word(img: Image.Image, size: int, scale: float) -> None: """把 "OA" 居中贴上去;scale 控制字形占画布的比例(maskable 要缩到安全区里)。""" draw = ImageDraw.Draw(img) text_font = font(int(size * scale)) box = draw.textbbox((0, 0), WORD, font=text_font) width, height = box[2] - box[0], box[3] - box[1] draw.text( ((size - width) / 2 - box[0], (size - height) / 2 - box[1]), WORD, font=text_font, fill=TEXT, ) def rounded(size: int, scale: float, radius_ratio: float | None) -> Image.Image: """radius_ratio=None → 铺满方图(iOS 自己会切圆角,maskable 也必须是方图)。""" img = gradient(size).convert("RGBA") draw_word(img, size, scale) if radius_ratio is None: return img mask = Image.new("L", (size, size), 0) ImageDraw.Draw(mask).rounded_rectangle( [0, 0, size - 1, size - 1], radius=int(size * radius_ratio), fill=255 ) img.putalpha(mask) return img def main() -> None: OUT_DIR.mkdir(parents=True, exist_ok=True) targets = ( # (文件名, 边长, 字形比例, 圆角比例) ("icon-192.png", 192, 0.42, 0.22), ("icon-512.png", 512, 0.42, 0.22), # maskable:内容必须落在中间 80% 的安全区里,且不许有透明通道 ("icon-maskable-192.png", 192, 0.30, None), ("icon-maskable-512.png", 512, 0.30, None), # iOS 加到桌面用:方图、不透明,系统自己蒙圆角 ("apple-touch-icon.png", 180, 0.40, None), ) for name, size, scale, radius in targets: image = rounded(size, scale, radius) if radius is None: image = image.convert("RGB") image.save(OUT_DIR / name) print(f"写入 public/icons/{name} {size}x{size}") if __name__ == "__main__": main()