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

运行 .9.png 外围 1px 像素规范解析、无失真缩放、内容 padding 计算与多段拉伸离线校验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-9-image.py
explore-tutorial-9-image.py206 行
"""Offline deterministic verifier for Android CH10 (tutorial-9-image)."""
from __future__ import annotations

import json
import re

BLACK = (0, 0, 0, 255)
TRANSPARENT = (0, 0, 0, 0)
FILL = (66, 133, 244, 255)


def make_nine_patch(
    inner_w: int,
    inner_h: int,
    top_stretch: list[tuple[int, int]],
    left_stretch: list[tuple[int, int]],
    bottom_content: tuple[int, int],
    right_content: tuple[int, int],
) -> list[list[tuple[int, int, int, int]]]:
    w, h = inner_w + 2, inner_h + 2
    grid = [[TRANSPARENT for _ in range(w)] for _ in range(h)]
    for y in range(1, h - 1):
        for x in range(1, w - 1):
            grid[y][x] = FILL
    for start, end in top_stretch:
        for x in range(start + 1, end + 1):
            grid[0][x] = BLACK
    for start, end in left_stretch:
        for y in range(start + 1, end + 1):
            grid[y][0] = BLACK
    for x in range(bottom_content[0] + 1, bottom_content[1] + 1):
        grid[h - 1][x] = BLACK
    for y in range(right_content[0] + 1, right_content[1] + 1):
        grid[y][w - 1] = BLACK
    return grid


def parse_spans(pixels: list[tuple[int, int, int, int]]) -> list[tuple[int, int]]:
    spans = []
    start = None
    for idx, px in enumerate(pixels):
        if px == BLACK and start is None:
            start = idx
        elif px != BLACK and start is not None:
            spans.append((start, idx))
            start = None
    if start is not None:
        spans.append((start, len(pixels)))
    return spans


def case_nine_patch_border_spec() -> dict:
    grid = make_nine_patch(
        inner_w=20,
        inner_h=20,
        top_stretch=[(4, 16)],
        left_stretch=[(4, 16)],
        bottom_content=(5, 15),
        right_content=(3, 17),
    )
    h, w = len(grid), len(grid[0])
    corners = [grid[0][0], grid[0][w - 1], grid[h - 1][0], grid[h - 1][w - 1]]
    top_spans = parse_spans(grid[0][1 : w - 1])
    left_spans = parse_spans([grid[y][0] for y in range(1, h - 1)])
    bottom_spans = parse_spans(grid[h - 1][1 : w - 1])
    right_spans = parse_spans([grid[y][w - 1] for y in range(1, h - 1)])
    actual = {
        "outer_dimensions": [w, h],
        "corners_all_transparent": all(c == TRANSPARENT for c in corners),
        "top_stretch_x": [list(s) for s in top_spans],
        "left_stretch_y": [list(s) for s in left_spans],
        "bottom_content_x": [list(s) for s in bottom_spans],
        "right_content_y": [list(s) for s in right_spans],
    }
    expected = {
        "outer_dimensions": [22, 22],
        "corners_all_transparent": True,
        "top_stretch_x": [[4, 16]],
        "left_stretch_y": [[4, 16]],
        "bottom_content_x": [[5, 15]],
        "right_content_y": [[3, 17]],
    }
    return {
        "name": "nine_patch_border_spec_parser",
        "summary": "解析 .9.png 外围 1px 边框黑线,核验左上拉伸、右下内容及四角透明规范",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_distortion_free_scaling() -> dict:
    inner_w, inner_h = 20, 20
    fixed_left, stretch_w, fixed_right = 4, 12, 4
    fixed_top, stretch_h, fixed_bottom = 4, 12, 4
    target_w, target_h = 120, 40
    scaled_stretch_w = target_w - fixed_left - fixed_right
    scaled_stretch_h = target_h - fixed_top - fixed_bottom
    actual = {
        "inner_sum_matches": (fixed_left + stretch_w + fixed_right == inner_w) and (fixed_top + stretch_h + fixed_bottom == inner_h),
        "corner_box_preserved": [fixed_left, fixed_top, fixed_right, fixed_bottom],
        "scaled_center_box": [scaled_stretch_w, scaled_stretch_h],
        "total_target_dims": [fixed_left + scaled_stretch_w + fixed_right, fixed_top + scaled_stretch_h + fixed_bottom],
    }
    expected = {
        "inner_sum_matches": True,
        "corner_box_preserved": [4, 4, 4, 4],
        "scaled_center_box": [112, 32],
        "total_target_dims": [120, 40],
    }
    return {
        "name": "nine_patch_distortion_free_scaling",
        "summary": "模拟 20x20 圆角按钮按 .9 拉伸至 120x40,验证四角保持 4x4 零失真且中间区等比扩展",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_padding_box_calculation() -> dict:
    inner_w, inner_h = 20, 20
    bottom_content = (5, 15)
    right_content = (3, 17)
    padding = {
        "left": bottom_content[0],
        "right": inner_w - bottom_content[1],
        "top": right_content[0],
        "bottom": inner_h - right_content[1],
    }
    target_w, target_h = 200, 60
    safe_content_rect = [
        padding["left"],
        padding["top"],
        target_w - padding["right"],
        target_h - padding["bottom"],
    ]
    actual = {
        "padding": padding,
        "safe_content_rect_200x60": safe_content_rect,
        "safe_content_size": [safe_content_rect[2] - safe_content_rect[0], safe_content_rect[3] - safe_content_rect[1]],
    }
    expected = {
        "padding": {"left": 5, "right": 5, "top": 3, "bottom": 3},
        "safe_content_rect_200x60": [5, 3, 195, 57],
        "safe_content_size": [190, 54],
    }
    return {
        "name": "nine_patch_padding_box_calculation",
        "summary": "由右下黑线推导 TextView 背景内边距 padding 及 200x60 目标尺寸下的安全文本绘制区",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_filename_and_multi_segment() -> dict:
    pattern = re.compile(r"^[a-z0-9_]+\.9\.png$")
    names = ["back.9.png", "chat_bubble_left.9.png", "Bad-Name.9.png", "normal.png"]
    valid = [n for n in names if pattern.match(n)]
    # Multi-segment stretch (e.g., speech bubble with fixed arrow at x=8..12)
    grid = make_nine_patch(
        inner_w=20,
        inner_h=16,
        top_stretch=[(3, 8), (12, 17)],
        left_stretch=[(4, 12)],
        bottom_content=(3, 17),
        right_content=(3, 13),
    )
    top_spans = parse_spans(grid[0][1 : len(grid[0]) - 1])
    actual = {
        "valid_filenames": valid,
        "bubble_top_stretch_segments": [list(s) for s in top_spans],
        "arrow_segment_preserved": top_spans == [(3, 8), (12, 17)],
        "compiled_png_chunk": "npTc",
    }
    expected = {
        "valid_filenames": ["back.9.png", "chat_bubble_left.9.png"],
        "bubble_top_stretch_segments": [[3, 8], [12, 17]],
        "arrow_segment_preserved": True,
        "compiled_png_chunk": "npTc",
    }
    return {
        "name": "nine_patch_filename_and_chunk_metadata",
        "summary": "验证 .9.png 命名规则、多段拉伸避让气泡尖角及 AAPT 编译生成的 npTc 块标识",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    payload = {
        "version": "CPython 3.12.14 offline Android XML/layout/manifest verifier (Android SDK/emulator absent)",
        "cases": [
            case_nine_patch_border_spec(),
            case_distortion_free_scaling(),
            case_padding_box_calculation(),
            case_filename_and_multi_segment(),
        ],
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


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

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

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

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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