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

验证 Drawable 命名正则、ARGB 颜色打包、NinePatch/Shape/Gradient XML 属性与 PathShape 布局

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-drawable1.py
explore-tutorial-drawable1.py201 行
"""Offline verification lab for Android Ch 105: tutorial-drawable1."""
import json
import re
import xml.etree.ElementTree as ET

VERSION = "CPython 3.12.14 offline Android socket/graphics/ColorMatrix verifier (Android SDK/emulator absent)"

NS = "{http://schemas.android.com/apk/res/android}"

COLOR_DRAWABLE_XML = """<?xml version="1.0" encoding="utf-8"?>
<color xmlns:android="http://schemas.android.com/apk/res/android" android:color="#FF0000"/>"""

COLORS_VALUES_XML = """<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="material_grey_100">#fff5f5f5</color>
    <color name="material_grey_300">#ffe0e0e0</color>
    <color name="material_grey_50">#fffafafa</color>
    <color name="material_grey_600">#ff757575</color>
    <color name="material_grey_800">#ff424242</color>
    <color name="material_grey_850">#ff303030</color>
    <color name="material_grey_900">#ff212121</color>
</resources>"""

NINEPATCH_XML = """<?xml version="1.0" encoding="utf-8"?>
<nine-patch xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/dule_pic"
    android:dither="true"/>"""

GRADIENT_LINEAR_XML = """<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <gradient android:angle="90" android:centerColor="#FFEB82" android:endColor="#35B2DE" android:startColor="#DEACAB" />
    <stroke android:dashGap="5dip" android:dashWidth="4dip" android:width="3dip" android:color="#fff" />
</shape>"""

GRADIENT_RADIAL_XML = """<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadius="0dip" android:shape="ring" android:thickness="70dip" android:useLevel="false">
    <gradient android:centerColor="#FFEB82" android:endColor="#35B2DE" android:gradientRadius="70"
        android:startColor="#DEACAB" android:type="radial" android:useLevel="false" />
</shape>"""

GRADIENT_SWEEP_XML = """<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadiusRatio="8" android:shape="ring" android:thicknessRatio="3" android:useLevel="false">
    <gradient android:centerColor="#FFEB82" android:endColor="#35B2DE"
        android:startColor="#DEACAB" android:type="sweep" android:useLevel="false" />
</shape>"""


def pack_argb(a: int, r: int, g: int, b: int) -> int:
    return ((a & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF)


def case_drawable_resource_naming_and_argb_color():
    pat = re.compile(r"^[a-z][a-z0-9_.]*$")
    names = {
        "btn_back_selector": bool(pat.match("btn_back_selector")),
        "1icon": bool(pat.match("1icon")),
        "BtnNormal": bool(pat.match("BtnNormal")),
        "pic_9.9": bool(pat.match("pic_9.9")),
    }
    c_root = ET.fromstring(COLOR_DRAWABLE_XML)
    res_root = ET.fromstring(COLORS_VALUES_XML)
    omitted_alpha = 0xFF0000
    opaque_red = pack_argb(0xFF, 0xFF, 0x00, 0x00)
    actual = {
        "naming_validation": names,
        "color_drawable_attr": c_root.attrib[NS + "color"],
        "values_color_count": len(res_root.findall("color")),
        "argb_opaque_red_hex": f"0x{opaque_red:08X}",
        "omitted_alpha_byte": (omitted_alpha >> 24) & 0xFF,
        "argb_black_hex": f"0x{pack_argb(0xFF, 0x00, 0x00, 0x00):08X}",
    }
    expected = {
        "naming_validation": {
            "btn_back_selector": True,
            "1icon": False,
            "BtnNormal": False,
            "pic_9.9": True,
        },
        "color_drawable_attr": "#FF0000",
        "values_color_count": 7,
        "argb_opaque_red_hex": "0xFFFF0000",
        "omitted_alpha_byte": 0,
        "argb_black_hex": "0xFF000000",
    }
    return {
        "name": "drawable_resource_naming_and_argb_color",
        "summary": "Verify Android drawable filename regex, ColorDrawable XML, colors.xml, and ARGB alpha packing",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_ninepatch_xml_and_bitmap_wrapper():
    root = ET.fromstring(NINEPATCH_XML)
    actual = {
        "tag": root.tag,
        "src": root.attrib[NS + "src"],
        "dither": root.attrib[NS + "dither"] == "true",
        "required_dir": "res/drawable",
        "requires_1px_black_border_in_aapt": True,
    }
    expected = {
        "tag": "nine-patch",
        "src": "@drawable/dule_pic",
        "dither": True,
        "required_dir": "res/drawable",
        "requires_1px_black_border_in_aapt": True,
    }
    return {
        "name": "ninepatch_xml_and_bitmap_wrapper",
        "summary": "Verify <nine-patch> XML attributes and AAPT NinePatch directory/border constraints",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_shape_and_gradient_xml_attributes():
    lin = ET.fromstring(GRADIENT_LINEAR_XML)
    rad = ET.fromstring(GRADIENT_RADIAL_XML)
    swp = ET.fromstring(GRADIENT_SWEEP_XML)
    lin_grad = lin.find("gradient")
    rad_grad = rad.find("gradient")
    swp_grad = swp.find("gradient")
    lin_stroke = lin.find("stroke")
    angle = int(lin_grad.attrib[NS + "angle"])
    actual = {
        "linear_shape": lin.attrib[NS + "shape"],
        "linear_angle_valid_mult45": angle % 45 == 0,
        "linear_stroke_dash": [lin_stroke.attrib[NS + "dashWidth"], lin_stroke.attrib[NS + "dashGap"]],
        "radial_type": rad_grad.attrib[NS + "type"],
        "radial_radius": int(rad_grad.attrib[NS + "gradientRadius"]),
        "sweep_shape": swp.attrib[NS + "shape"],
        "sweep_ratios": [int(swp.attrib[NS + "innerRadiusRatio"]), int(swp.attrib[NS + "thicknessRatio"])],
    }
    expected = {
        "linear_shape": "oval",
        "linear_angle_valid_mult45": True,
        "linear_stroke_dash": ["4dip", "5dip"],
        "radial_type": "radial",
        "radial_radius": 70,
        "sweep_shape": "ring",
        "sweep_ratios": [8, 3],
    }
    return {
        "name": "shape_and_gradient_xml_attributes",
        "summary": "Verify <shape> and <gradient> XML attributes for linear, radial, and sweep gradients",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_programmatic_shape_drawable_bounds_and_path():
    x, y, width, height = 10, 10, 400, 100
    bounds = []
    for _ in range(7):
        bounds.append((x, y, x + width, y + height))
        y += height + 5
    diamond = [(50, 0), (0, 50), (50, 100), (100, 50)]
    # Shoelace area of diamond
    area = 0.5 * abs(
        sum(diamond[i][0] * diamond[(i + 1) % 4][1] - diamond[(i + 1) % 4][0] * diamond[i][1] for i in range(4))
    )
    actual = {
        "drawable_count": len(bounds),
        "first_bounds": list(bounds[0]),
        "last_bounds": list(bounds[-1]),
        "diamond_path_area": int(area),
    }
    expected = {
        "drawable_count": 7,
        "first_bounds": [10, 10, 410, 110],
        "last_bounds": [10, 640, 410, 740],
        "diamond_path_area": 5000,
    }
    return {
        "name": "programmatic_shape_drawable_bounds_and_path",
        "summary": "Verify 7 programmatic ShapeDrawable vertical bounds stack and 100x100 diamond PathShape area",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_drawable_resource_naming_and_argb_color(),
        case_ninepatch_xml_and_bitmap_wrapper(),
        case_shape_and_gradient_xml_attributes(),
        case_programmatic_shape_drawable_bounds_and_path(),
    ]
    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-drawable1-lab/explore-tutorial-drawable1.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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