蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

8.3.10 Paint API 之—— ColorFilter(颜色过滤器)(2/3)

解析 LightingColorFilter 光照色彩过滤器的精确 Skia 逐通道乘加截断公式、Alpha 不变性、典型滤色参数组合及十六进制输入解析注意点。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

LightingColorFilter 精确乘加公式与典型滤色效果

`LightingColorFilter(int mul, int add)` 是 `ColorFilter` 的第二个子类,用于以极低开销模拟单色光照过滤与高亮叠加效果。两个参数均按 `0x00RRGGBB` 解析出红、绿、蓝三通道字节(高 8 位 Alpha 被忽略,且原图像素的 Alpha 通道全程保持不变)。在 Android/Skia 底层,R、G、B 三个通道分别按精确公式 `C' = clamp((C * mul_c) / 255 + add_c, 0, 255)` 运算并截断至 `[0, 255]`(注意原文简写为 `(RGB * mul + Add) % 255` 存在取模误笔,实际超过 `255` 是饱和截断而非循环回绕)。据此:`mul = 0xFFFFFF, add = 0x000000` 保持原图不变;`mul = 0xFFFF00, add = 0x000000` 可过滤掉全部蓝色通道呈现暖黄;`mul = 0xFFFFFF, add = 0x003000` 可叠加绿色高光;`mul = 0x000000, add = 0xFF0000` 则将所有可见像素染成纯红并保留原透明度轮廓。

交互演示代码与输入解析细节

演示布局 `activity_main.xml` 放置预览 `ImageView`、两个参数输入框 `edit_mul`/`edit_add` 与触发按钮 `btn_change`;`MainActivity` 中的 `ProcessImage(bp, mul, add)` 新建 `ARGB_8888` 目标位图,为 `Paint` 设置 `new LightingColorFilter(mul, add)` 后经 `Canvas.drawBitmap()` 完成重绘。实际交互时需注意:示例中 `Integer.parseInt(text)` 默认按十进制解析,若在输入框中直接填写十六进制色值(如 `FFFF00`)会抛出 `NumberFormatException`,工程上应显式指定基数 `Integer.parseInt(text, 16)` 并做好异常捕获。源示例包 `LightingColorFilterDemo.zip` 未联网下载并已登记;本站离线实验对精确 Skia 公式、四类典型滤色及 Alpha 保持进行了逐项实测。

验证 LightingColorFilter Skia 乘加截断公式、滤蓝/增绿/纯色染色与 Alpha 不变性

python · 阅读源码
"""Offline verification lab for Android Ch 119: tutorial-colorfilterl2."""
import json
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}"

LAYOUT_XML = """<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:padding="5dp" tools:context=".MainActivity">
    <ImageView android:id="@+id/img_meizi" android:layout_width="300dp" android:layout_height="300dp" android:src="@mipmap/img_demo" />
    <EditText android:id="@+id/edit_mul" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0" />
    <EditText android:id="@+id/edit_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0" />
    <Button android:id="@+id/btn_change" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="变化" />
</RelativeLayout>"""


def lighting_filter(argb, mul: int, add: int):
    a, r, g, b = argb
    mr, mg, mb = (mul >> 16) & 0xFF, (mul >> 8) & 0xFF, mul & 0xFF
    ar, ag, ab = (add >> 16) & 0xFF, (add >> 8) & 0xFF, add & 0xFF
    nr = min(255, max(0, (r * mr) // 255 + ar))
    ng = min(255, max(0, (g * mg) // 255 + ag))
    nb = min(255, max(0, (b * mb) // 255 + ab))
    return [a, nr, ng, nb]


def case_lighting_color_filter_exact_skia_formula():
    px = [255, 200, 120, 80]
    # Multiply red by 1.0 (0xFF), green by ~0.5 (0x80), blue by 0 (0x00), add +30 green
    out = lighting_filter(px, 0xFF8000, 0x001E00)
    # Contrast with clamping (not modulo % 255!) when result exceeds 255
    clamped = lighting_filter(px, 0xFFFFFF, 0x640000)  # 200 + 100 = 300 -> clamped to 255
    actual = {
        "filtered_argb": out,
        "clamped_overflow_argb": clamped,
        "uses_clamp_0_255_not_modulo": clamped[1] == 255,
    }
    expected = {
        "filtered_argb": [255, 200, 90, 0],
        "clamped_overflow_argb": [255, 255, 120, 80],
        "uses_clamp_0_255_not_modulo": True,
    }
    return {
        "name": "lighting_color_filter_exact_skia_formula",
        "summary": "Verify Skia LightingColorFilter per-channel clamp((C*mul_c)//255 + add_c, 0, 255) math",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_lighting_filter_identity_tint_and_channel_removal():
    px = [255, 180, 140, 100]
    actual = {
        "identity_0xFFFFFF_0x000000": lighting_filter(px, 0xFFFFFF, 0x000000),
        "remove_blue_yellow_tint": lighting_filter(px, 0xFFFF00, 0x000000),
        "add_green_highlight": lighting_filter(px, 0xFFFFFF, 0x003000),
        "solid_red_flood": lighting_filter(px, 0x000000, 0xFF0000),
    }
    expected = {
        "identity_0xFFFFFF_0x000000": [255, 180, 140, 100],
        "remove_blue_yellow_tint": [255, 180, 140, 0],
        "add_green_highlight": [255, 180, 188, 100],
        "solid_red_flood": [255, 255, 0, 0],
    }
    return {
        "name": "lighting_filter_identity_tint_and_channel_removal",
        "summary": "Verify LightingColorFilter identity, blue channel removal, green boost, and solid color flood",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_lighting_filter_alpha_invariance_and_clamp():
    semi_px = [128, 200, 150, 100]
    out = lighting_filter(semi_px, 0xFFFFFF, 0x646464)
    actual = {
        "input_alpha": semi_px[0],
        "output_alpha_unchanged": out[0],
        "output_argb": out,
    }
    expected = {
        "input_alpha": 128,
        "output_alpha_unchanged": 128,
        "output_argb": [128, 255, 250, 200],
    }
    return {
        "name": "lighting_filter_alpha_invariance_and_clamp",
        "summary": "Verify LightingColorFilter leaves Alpha untouched and clamps RGB channels at 255",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_layout_and_hex_input_parsing_caveat():
    root = ET.fromstring(LAYOUT_XML)
    ids = [c.attrib[NS + "id"] for c in root if (NS + "id") in c.attrib]
    hex_str = "FFFF00"
    parsed_hex = int(hex_str, 16)
    dec_fails = False
    try:
        int(hex_str, 10)
    except ValueError:
        dec_fails = True
    actual = {
        "layout_ids": ids,
        "hex_FFFF00_value": parsed_hex,
        "base10_parseInt_rejects_hex_letters": dec_fails,
    }
    expected = {
        "layout_ids": ["@+id/img_meizi", "@+id/edit_mul", "@+id/edit_add", "@+id/btn_change"],
        "hex_FFFF00_value": 16776960,
        "base10_parseInt_rejects_hex_letters": True,
    }
    return {
        "name": "layout_and_hex_input_parsing_caveat",
        "summary": "Verify layout widget IDs and radix-16 parsing requirement for hex color inputs",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_lighting_color_filter_exact_skia_formula(),
        case_lighting_filter_identity_tint_and_channel_removal(),
        case_lighting_filter_alpha_invariance_and_clamp(),
        case_layout_and_hex_input_parsing_caveat(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 0xFF8000+0x001E00 像素变换、溢出截断至 255 而非取模、半透明 Alpha=128 保持不变及基数 16 解析。
验证 LightingColorFilter Skia 乘加截断公式、滤蓝/增绿/纯色染色与 Alpha 不变性

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

当前源码 SHA256:74041fb578beeb3d2d47ab2d6b9fb8602495ddcdbf614a38573fcce2bea26050

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载8.3.10 Paint API 之—— ColorFilter(颜色过滤器)(2/3)实验

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

ZIP SHA256:73b8a50ab61b9ebc299acd43d169c5eeace5ff2c64a87660ce8f3ffef8ca705a

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 LightingColorFilter(mul, add) 中,如果想完全去掉图片中的蓝色分量并保留红绿原色,mul 与 add 应分别传入什么十六进制值?原图透明度会受影响吗?

展开参考解答

应传入 mul = 0xFFFF00、add = 0x000000;LightingColorFilter 只变换 R、G、B 三通道并截断在 0–255,原像素的 Alpha 通道完全不受影响。

规范与官方依据