蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 Typeface 风格位掩码、系统字族预设、assets 路径与现代字重边界核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-typeface.py
explore-tutorial-typeface.py147 行
"""Offline Android graphics verifier for Ch 124: Paint Typeface."""
from dataclasses import dataclass
import json

VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"

NORMAL = 0
BOLD = 1
ITALIC = 2
BOLD_ITALIC = 3


@dataclass(frozen=True)
class TypefaceModel:
    family: str
    style: int
    source: str

    @property
    def is_bold(self) -> bool:
        return bool(self.style & BOLD)

    @property
    def is_italic(self) -> bool:
        return bool(self.style & ITALIC)


def create_from_asset(asset_path: str) -> TypefaceModel:
    if not asset_path.lower().endswith((".ttf", ".otf")):
        raise ValueError("Unsupported font asset extension")
    if asset_path.startswith("/"):
        raise ValueError("Asset path must be relative to assets/")
    return TypefaceModel(family=asset_path.split("/")[-1], style=NORMAL, source=f"assets/{asset_path}")


def main() -> None:
    # Case 1: Typeface style bitmask constants (NORMAL=0, BOLD=1, ITALIC=2, BOLD_ITALIC=3)
    c1_actual = {
        "constants": {"NORMAL": NORMAL, "BOLD": BOLD, "ITALIC": ITALIC, "BOLD_ITALIC": BOLD_ITALIC},
        "bold_or_italic_eq_bold_italic": (BOLD | ITALIC) == BOLD_ITALIC,
        "flags": {
            "NORMAL": [bool(NORMAL & BOLD), bool(NORMAL & ITALIC)],
            "BOLD": [bool(BOLD & BOLD), bool(BOLD & ITALIC)],
            "ITALIC": [bool(ITALIC & BOLD), bool(ITALIC & ITALIC)],
            "BOLD_ITALIC": [bool(BOLD_ITALIC & BOLD), bool(BOLD_ITALIC & ITALIC)],
        },
    }
    c1_expected = {
        "constants": {"NORMAL": 0, "BOLD": 1, "ITALIC": 2, "BOLD_ITALIC": 3},
        "bold_or_italic_eq_bold_italic": True,
        "flags": {
            "NORMAL": [False, False],
            "BOLD": [True, False],
            "ITALIC": [False, True],
            "BOLD_ITALIC": [True, True],
        },
    }

    # Case 2: 5 static Typeface singletons across 3 system families (sans, serif, monospace)
    presets = {
        "DEFAULT": TypefaceModel("sans-serif", NORMAL, "system"),
        "DEFAULT_BOLD": TypefaceModel("sans-serif", BOLD, "system"),
        "MONOSPACE": TypefaceModel("monospace", NORMAL, "system"),
        "SANS_SERIF": TypefaceModel("sans-serif", NORMAL, "system"),
        "SERIF": TypefaceModel("serif", NORMAL, "system"),
    }
    c2_actual = {
        "preset_count": len(presets),
        "distinct_families": sorted({tf.family for tf in presets.values()}),
        "default_bold_is_bold": presets["DEFAULT_BOLD"].is_bold,
        "monospace_style": presets["MONOSPACE"].style,
    }
    c2_expected = {
        "preset_count": 5,
        "distinct_families": ["monospace", "sans-serif", "serif"],
        "default_bold_is_bold": True,
        "monospace_style": 0,
    }

    # Case 3: createFromAsset("font/MONACO.ttf") path resolution & MyView 5-line draw layout
    monaco = create_from_asset("font/MONACO.ttf")
    rows = [
        {"y": 100 * (i + 1), "size": 100, "typeface": name}
        for i, name in enumerate(["DEFAULT_BOLD", "MONOSPACE", "SANS_SERIF", "SERIF", monaco.family])
    ]
    c3_actual = {
        "asset_source": monaco.source,
        "asset_style": monaco.style,
        "draw_y_positions": [r["y"] for r in rows],
        "fifth_line_family": rows[4]["typeface"],
    }
    c3_expected = {
        "asset_source": "assets/font/MONACO.ttf",
        "asset_style": 0,
        "draw_y_positions": [100, 200, 300, 400, 500],
        "fifth_line_family": "MONACO.ttf",
    }

    # Case 4: API 26+ res/font resource naming & API 28 Typeface.create(base, weight, italic) clamping
    def resolve_weight(weight: int) -> int:
        return max(1, min(1000, weight))

    c4_actual = {
        "valid_res_font_name": "monaco.ttf".islower() and "monaco.ttf".endswith(".ttf"),
        "clamped_weights": [resolve_weight(0), resolve_weight(400), resolve_weight(700), resolve_weight(1200)],
    }
    c4_expected = {
        "valid_res_font_name": True,
        "clamped_weights": [1, 400, 700, 1000],
    }

    cases = [
        {
            "name": "typeface_style_bitmasks",
            "summary": "核验 Typeface 四项整型风格常量(NORMAL=0/BOLD=1/ITALIC=2/BOLD_ITALIC=3)的位掩码组合关系",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "system_typeface_presets",
            "summary": "核验系统 5 个静态 Typeface 对象与 sans-serif/serif/monospace 三大内置字族映射",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "create_from_asset_and_myview_rows",
            "summary": "核验 createFromAsset(\"font/MONACO.ttf\") 路径规则及 MyView 5 行文本的纵向基线排布",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "modern_font_resource_and_weight",
            "summary": "核验 API 26+ res/font 小写资源命名与 API 28 连续字重 [1, 1000] 边界约束",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-typeface-lab/explore-tutorial-typeface.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-typeface.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1962.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习