"""Offline verification lab for Android Ch 118: tutorial-colorfilter1."""
import json
import math
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}"
GRID_LAYOUT_XML = """<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp">
<ImageView android:id="@+id/img_show" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="2" />
<GridLayout android:id="@+id/gp_matrix" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="3"
android:columnCount="5" android:rowCount="4"></GridLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<Button android:id="@+id/btn_reset" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="重置" />
<Button android:id="@+id/btn_Change" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="变换" />
</LinearLayout>
</LinearLayout>"""
SEEKBAR_LAYOUT_XML = """<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp">
<ImageView android:id="@+id/img_meizi" android:layout_width="300dp" android:layout_height="300dp" />
<SeekBar android:id="@+id/sb_hue" android:layout_width="match_parent" android:layout_height="32dp" />
<SeekBar android:id="@+id/sb_saturation" android:layout_width="match_parent" android:layout_height="32dp" />
<SeekBar android:id="@+id/sb_lum" android:layout_width="match_parent" android:layout_height="32dp" />
</RelativeLayout>"""
def clamp255(v: float) -> int:
return max(0, min(255, round(v)))
def identity_cm():
return [1.0 if i % 6 == 0 else 0.0 for i in range(20)]
def apply_cm(m, rgba):
r, g, b, a = rgba
out = []
for row in range(4):
i = row * 5
val = m[i] * r + m[i + 1] * g + m[i + 2] * b + m[i + 3] * a + m[i + 4]
out.append(clamp255(val))
return out
def cm_set_rotate(axis: int, degrees: float):
m = identity_cm()
rad = math.radians(degrees)
c, s = math.cos(rad), math.sin(rad)
if axis == 0:
m[6], m[7], m[11], m[12] = c, s, -s, c
elif axis == 1:
m[0], m[2], m[10], m[12] = c, -s, s, c
elif axis == 2:
m[0], m[1], m[5], m[6] = c, s, -s, c
return m
def cm_set_saturation(sat: float):
m = identity_cm()
inv = 1.0 - sat
r, g, b = 0.213 * inv, 0.715 * inv, 0.072 * inv
m[0], m[1], m[2] = r + sat, g, b
m[5], m[6], m[7] = r, g + sat, b
m[10], m[11], m[12] = r, g, b + sat
return m
def cm_set_scale(rs: float, gs: float, bs: float, as_: float):
m = [0.0] * 20
m[0], m[6], m[12], m[18] = rs, gs, bs, as_
return m
def cm_concat(mat_a, mat_b):
# Computes mat_a * mat_b (postConcat(X) sets self = X * self)
out = [0.0] * 20
for j in range(4):
for i in range(4):
out[j * 5 + i] = sum(mat_a[j * 5 + k] * mat_b[k * 5 + i] for k in range(4))
out[j * 5 + 4] = sum(mat_a[j * 5 + k] * mat_b[k * 5 + 4] for k in range(4)) + mat_a[j * 5 + 4]
return out
def case_colormatrix_4x5_affine_pixel_math():
px = [100, 150, 80, 255]
ident = identity_cm()
blue_boost = identity_cm()
blue_boost[12] = 2.0
sepia = [
0.393, 0.769, 0.189, 0, 0,
0.349, 0.686, 0.168, 0, 0,
0.272, 0.534, 0.131, 0, 0,
0, 0, 0, 1, 0,
]
actual = {
"identity_indices_1": [i for i, v in enumerate(ident) if v == 1.0],
"identity_rgba": apply_cm(ident, px),
"blue_x2_rgba": apply_cm(blue_boost, px),
"sepia_rgba": apply_cm(sepia, px),
}
expected = {
"identity_indices_1": [0, 6, 12, 18],
"identity_rgba": [100, 150, 80, 255],
"blue_x2_rgba": [100, 150, 160, 255],
"sepia_rgba": [170, 151, 118, 255],
}
return {
"name": "colormatrix_4x5_affine_pixel_math",
"summary": "Verify 4x5 ColorMatrix identity (i%6==0), blue channel scaling, and sepia affine pixel transform",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_colormatrix_rotate_saturation_scale_and_postconcat():
px = [200, 100, 50, 255]
# Grayscale via setSaturation(0)
gray_m = cm_set_saturation(0.0)
gray_px = apply_cm(gray_m, px)
# Luminance scale 0.5
lum_m = cm_set_scale(0.5, 0.5, 0.5, 1.0)
# postConcat: lum_m * gray_m
composed = cm_concat(lum_m, gray_m)
composed_px = apply_cm(composed, px)
# Note: Android ColorMatrix.setRotate resets matrix each time, so calling setRotate(0), setRotate(1), setRotate(2) keeps only axis=2
rot_b90 = cm_set_rotate(2, 90.0)
rot_px = apply_cm(rot_b90, px)
actual = {
"desaturated_gray": gray_px,
"postConcat_gray_then_half_lum": composed_px,
"rotate_axis2_90deg": rot_px,
"setRotate_resets_previous_axes": True,
}
expected = {
"desaturated_gray": [118, 118, 118, 255],
"postConcat_gray_then_half_lum": [59, 59, 59, 255],
"rotate_axis2_90deg": [100, 0, 50, 255],
"setRotate_resets_previous_axes": True,
}
return {
"name": "colormatrix_rotate_saturation_scale_and_postconcat",
"summary": "Verify ColorMatrix setSaturation, setScale, setRotate(axis,deg), and postConcat matrix multiplication",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_seekbar_progress_to_hsl_parameter_mapping():
mid = 127
def map_params(p: int):
hue = round((p - mid) * 1.0 / mid * 180.0, 2)
sat = round(p * 1.0 / mid, 3)
lum = round(p * 1.0 / mid, 3)
return [hue, sat, lum]
actual = {
"progress_0": map_params(0),
"progress_127_neutral": map_params(127),
"progress_255_max": map_params(255),
}
expected = {
"progress_0": [-180.0, 0.0, 0.0],
"progress_127_neutral": [0.0, 1.0, 1.0],
"progress_255_max": [181.42, 2.008, 2.008],
}
return {
"name": "seekbar_progress_to_hsl_parameter_mapping",
"summary": "Verify SeekBar progress (0, 127, 255) mapping to hue, saturation, and luminance",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_gridlayout_4x5_and_post_measurement_layout():
g_root = ET.fromstring(GRID_LAYOUT_XML)
grid = g_root.find("GridLayout")
cols = int(grid.attrib[NS + "columnCount"])
rows = int(grid.attrib[NS + "rowCount"])
s_root = ET.fromstring(SEEKBAR_LAYOUT_XML)
seekbars = [sb.attrib[NS + "id"] for sb in s_root.findall("SeekBar")]
grid_w, grid_h = 1000, 600
actual = {
"grid_dims": [rows, cols],
"edittext_count": rows * cols,
"post_cell_wh": [grid_w // cols, grid_h // rows],
"seekbar_ids": seekbars,
}
expected = {
"grid_dims": [4, 5],
"edittext_count": 20,
"post_cell_wh": [200, 150],
"seekbar_ids": ["@+id/sb_hue", "@+id/sb_saturation", "@+id/sb_lum"],
}
return {
"name": "gridlayout_4x5_and_post_measurement_layout",
"summary": "Verify 4x5 GridLayout post() cell sizing and 3-SeekBar HSL layout XML",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_colormatrix_4x5_affine_pixel_math(),
case_colormatrix_rotate_saturation_scale_and_postconcat(),
case_seekbar_progress_to_hsl_parameter_mapping(),
case_gridlayout_4x5_and_post_measurement_layout(),
]
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-colorfilter1-lab/explore-tutorial-colorfilter1.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-colorfilter1.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1856.zip
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip