157 lines
6.2 KiB
Python
157 lines
6.2 KiB
Python
|
|
#!/usr/bin/env python3
|
|||
|
|
"""Pixelschrift aus einer TTF/OTF rastern — gleiche Schnittstelle wie `font8`.
|
|||
|
|
|
|||
|
|
Der Grund: eine bei 8 px gezeichnete Schrift dreifach zu setzen ergibt Balken
|
|||
|
|
(siehe `prep/font24/README.md`). Eine **bei 24 px gezeichnete** Schrift, die
|
|||
|
|
man bei 24 px rastert, ist dagegen scharf, weil jedes Pixel ein Pixel bleibt.
|
|||
|
|
|
|||
|
|
Gerastert wird in zwei Schritten: FreeType mit Kantenglättung, danach Schwelle
|
|||
|
|
bei 50 % (`_HART`). Bei einem Pixelfont auf seinem Designraster ist das
|
|||
|
|
Ergebnis pixelgenau; auf krummen Größen franst es — deshalb immer
|
|||
|
|
Designgröße × 1/2/3 verwenden.
|
|||
|
|
|
|||
|
|
from font_ttf import Font
|
|||
|
|
f = Font("prep/font24/ttf/PressStart2P-Regular.ttf", 24)
|
|||
|
|
f.draw_text(im, 0, 0, "Der Ghul greift an.", (226, 209, 176, 255))
|
|||
|
|
f.text_width("...") # Vorschub ist proportional, nicht fest
|
|||
|
|
|
|||
|
|
`advance(ch)` gibt den Vorschub eines Zeichens; `LINE` ist Zeilenhöhe.
|
|||
|
|
"""
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
from PIL import Image, ImageDraw, ImageFont
|
|||
|
|
|
|||
|
|
_HART = 127
|
|||
|
|
|
|||
|
|
|
|||
|
|
class Font:
|
|||
|
|
def __init__(self, pfad: str | Path, size: int) -> None:
|
|||
|
|
self.pfad = Path(pfad)
|
|||
|
|
self.size = size
|
|||
|
|
self.ttf = ImageFont.truetype(str(self.pfad), size)
|
|||
|
|
asc, desc = self.ttf.getmetrics()
|
|||
|
|
self.LINE = int(asc + desc)
|
|||
|
|
self._cache: dict[str, Image.Image] = {}
|
|||
|
|
self._versatz: dict[str, tuple[int, int]] = {}
|
|||
|
|
|
|||
|
|
# -- Raster -----------------------------------------------------------
|
|||
|
|
def glyph(self, ch: str) -> Image.Image:
|
|||
|
|
"""Zeichen als L-Maske, samt Versatz zur Grundlinie (x0, y0)."""
|
|||
|
|
if ch not in self._cache:
|
|||
|
|
m = self.ttf.getmask(ch, mode="L")
|
|||
|
|
im = Image.frombytes("L", m.size, bytes(m)).point(
|
|||
|
|
lambda v: 255 if v > _HART else 0)
|
|||
|
|
bb = self.ttf.getbbox(ch) or (0, 0, im.size[0], im.size[1])
|
|||
|
|
self._cache[ch] = im
|
|||
|
|
self._versatz[ch] = (bb[0], bb[1])
|
|||
|
|
return self._cache[ch]
|
|||
|
|
|
|||
|
|
def advance(self, ch: str) -> int:
|
|||
|
|
return int(round(self.ttf.getlength(ch)))
|
|||
|
|
|
|||
|
|
def ink(self, ch: str) -> tuple[Image.Image, tuple[int, int]]:
|
|||
|
|
"""Tintenflaeche eines Zeichens und ihr Versatz ab Zeilenoberkante.
|
|||
|
|
|
|||
|
|
Fuer den BMFont-Export: `xoffset`/`yoffset` sind genau dieser Versatz,
|
|||
|
|
`width`/`height` die Groesse der Maske.
|
|||
|
|
"""
|
|||
|
|
return self.glyph(ch), self._versatz.get(ch) or self._hole_versatz(ch)
|
|||
|
|
|
|||
|
|
# -- Satz -------------------------------------------------------------
|
|||
|
|
def _hole_versatz(self, ch: str) -> tuple[int, int]:
|
|||
|
|
self.glyph(ch)
|
|||
|
|
return self._versatz[ch]
|
|||
|
|
|
|||
|
|
def text_width(self, text: str) -> int:
|
|||
|
|
return sum(self.advance(c) for c in text)
|
|||
|
|
|
|||
|
|
def draw_text(self, ziel, x: int, y: int, text: str, color) -> int:
|
|||
|
|
"""Zeichnet Text; `ziel` darf ImageDraw oder Image sein."""
|
|||
|
|
bild = ziel if isinstance(ziel, Image.Image) else getattr(ziel, "_image", None)
|
|||
|
|
if not isinstance(bild, Image.Image):
|
|||
|
|
raise TypeError("draw_text braucht ein Image oder ImageDraw")
|
|||
|
|
rgba = bild if bild.mode == "RGBA" else bild.convert("RGBA")
|
|||
|
|
a = color[3] if len(color) > 3 else 255
|
|||
|
|
for ch in text:
|
|||
|
|
g = self.glyph(ch)
|
|||
|
|
dx, dy = self._versatz[ch]
|
|||
|
|
if g.size[0] and g.size[1]:
|
|||
|
|
farbe = Image.new("RGBA", g.size, tuple(color[:3]) + (255,))
|
|||
|
|
farbe.putalpha(g if a == 255
|
|||
|
|
else g.point(lambda v: v * a // 255))
|
|||
|
|
rgba.alpha_composite(farbe, (x + dx, y + dy))
|
|||
|
|
x += self.advance(ch)
|
|||
|
|
return x
|
|||
|
|
|
|||
|
|
def wrap(self, text: str, max_px: int) -> list[str]:
|
|||
|
|
words, lines, cur = text.split(), [], ""
|
|||
|
|
for w in words:
|
|||
|
|
cand = w if not cur else f"{cur} {w}"
|
|||
|
|
if self.text_width(cand) <= max_px:
|
|||
|
|
cur = cand
|
|||
|
|
else:
|
|||
|
|
if cur:
|
|||
|
|
lines.append(cur)
|
|||
|
|
cur = w
|
|||
|
|
if cur:
|
|||
|
|
lines.append(cur)
|
|||
|
|
return lines
|
|||
|
|
|
|||
|
|
# -- Bericht ----------------------------------------------------------
|
|||
|
|
def info(self) -> str:
|
|||
|
|
bb = self.ttf.getbbox("H")
|
|||
|
|
fehlt = [c for c in "ÄÖÜäöüß.,;:!?" if self.glyph(c).getbbox() is None]
|
|||
|
|
return (f"{self.pfad.name} @{self.size}px: Vorschub {self.advance('M')}, "
|
|||
|
|
f"capH {bb[3] - bb[1]}, Zeile {self.LINE}"
|
|||
|
|
+ (f", FEHLT: {''.join(fehlt)}" if fehlt else ""))
|
|||
|
|
|
|||
|
|
|
|||
|
|
# --------------------------------------------------------------- Vorschau ----
|
|||
|
|
|
|||
|
|
def _vorschau(f: Font, text: str | None, out: Path) -> None:
|
|||
|
|
"""Probesatz: Probetext, Alphabet, Umlaute — auf UI-Panel."""
|
|||
|
|
import ui # nur fuer Farben und den 8x10-Beschriftungssatz
|
|||
|
|
|
|||
|
|
zeilen = ([text] if text else
|
|||
|
|
["Valyria zahlt in Ferrum, nicht in Gold.",
|
|||
|
|
"Der Ghul greift an - haltet die Fackel!",
|
|||
|
|
"ÄÖÜäöüß 0123456789 .,;:!? \"()[]"])
|
|||
|
|
zeilen += ["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"]
|
|||
|
|
breit = max(f.text_width(z) for z in zeilen) + 24
|
|||
|
|
hoch = int(f.LINE * 1.35 * len(zeilen)) + 44
|
|||
|
|
im = Image.new("RGBA", (breit, hoch), ui.alpha(ui.PANEL))
|
|||
|
|
d = ImageDraw.Draw(im)
|
|||
|
|
h = f.LINE * 1.35
|
|||
|
|
for i, z in enumerate(zeilen):
|
|||
|
|
f.draw_text(im, 12, int(10 + i * h), z, ui.CREAM)
|
|||
|
|
ui.draw_text(d, 12, hoch - 24,
|
|||
|
|
f"{f.pfad.name} @{f.size}px Vorschub {f.advance('M')} "
|
|||
|
|
f"Zeile {f.LINE}", ui.CREAM_D)
|
|||
|
|
im.convert("RGB").save(out)
|
|||
|
|
print(f"{out} {im.width}x{im.height}")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main(argv: list[str] | None = None) -> int:
|
|||
|
|
import argparse
|
|||
|
|
import sys
|
|||
|
|
|
|||
|
|
ap = argparse.ArgumentParser(
|
|||
|
|
description="Probesatz einer TTF/OTF rendern — ohne Installation.")
|
|||
|
|
ap.add_argument("font", type=Path)
|
|||
|
|
ap.add_argument("--size", type=int, default=24,
|
|||
|
|
help="Rastergroesse in px (Designgroesse der Schrift!)")
|
|||
|
|
ap.add_argument("--text", help="eigener Probetext statt Alphabet")
|
|||
|
|
ap.add_argument("-o", "--out", type=Path, help="Ziel-PNG")
|
|||
|
|
a = ap.parse_args(argv)
|
|||
|
|
f = Font(a.font, a.size)
|
|||
|
|
out = a.out or Path(f"/tmp/font_{a.font.stem}_{a.size}px.png")
|
|||
|
|
_vorschau(f, a.text, out)
|
|||
|
|
return 0
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
import sys
|
|||
|
|
sys.exit(main())
|