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

8.3.9 Paint API 之—— ColorFilter(颜色过滤器)(1/3)

系统解析 ColorFilter 体系与 ColorMatrixColorFilter 4×5 颜色矩阵线性变换数学,并演练 4×5 矩阵编辑器与色调/饱和度/亮度三滑块图像调色实战。

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

学完这一章,你能够

ColorFilter 体系、RGBA 模型与 4×5 ColorMatrix 数学

继 `MaskFilter` 之后,本节起系统学习 `Paint.setColorFilter(ColorFilter)` 及其三大子类:`ColorMatrixColorFilter`(颜色矩阵过滤器)、`LightingColorFilter`(光照色彩过滤器)与 `PorterDuffColorFilter`(混排颜色过滤器)。理解颜色变换需先区分光的加色三基色 RGBA(红 Red、绿 Green、蓝 Blue 与透明度 Alpha,不同于颜料减色三原色),以及调色核心三维度:色调/色相(Hue,色轮上的颜色种类)、饱和度(Saturation,从 `0` 灰度到高纯度的色彩鲜艳度)与亮度/明度(Luminance,颜色的相对明暗程度)。

`ColorMatrix` 采用一个按行优先存储的 20 元素 `4×5` 浮点矩阵对每个像素的列向量 `[R, G, B, A, 1]^T` 执行仿射线性变换:每行前 4 个系数分别对原像素 `R、G、B、A` 加权,第 5 列为偏移量(范围通常在 `-255..255`),计算结果截断至 `[0, 255]`。单位矩阵满足索引 `i % 6 == 0`(即 `0, 6, 12, 18`)为 `1`、其余为 `0`;只需修改对角线或行系数即可快速实现泛蓝(如 `m[12] = 2`)、去色黑白、高对比度或泛黄复古(Sepia)滤镜。

4×5 矩阵编辑验证与色调/饱和度/亮度 API 实战

第一个案例构建了交互式 `4×5` 颜色矩阵编辑器:布局上方为展示 `ImageView`,中部为 `4 行 5 列` 的 `GridLayout`,底部为“重置”与“变换”按钮。在 `MainActivity.onCreate()` 中需借助 `gp_matrix.post(Runnable)` 等待 `GridLayout` 完成测量后再计算每格宽高 `w/5`、`h/4` 并动态填入 20 个 `EditText`;点击变换后读取 20 个浮点值构造 `ColorMatrixColorFilter`,经离屏 `Canvas` 重绘出滤镜结果。若不想手算 20 个矩阵元素,可直接调用 `ColorMatrix` 提供的三个高层方法:`setRotate(axis, degrees)`(调色调)、`setSaturation(sat)`(调饱和度)与 `setScale(rScale, gScale, bScale, aScale)`(调亮度)。

第二个案例封装 `ImageHelper.handleImageEffect(bm, hue, saturation, lum)` 并配合三条 `SeekBar`(`MAX_VALUE=255`,中性基准 `MID_VALUE=127`)实时换算 `hue = (p - 127) / 127f * 180`、`saturation = p / 127f`、`lum = p / 127f`,再以 `imageMatrix.postConcat(...)` 依次串联色调、饱和度与亮度矩阵。核对源码需留意一处重要 API 行为:`ColorMatrix.setRotate(axis, degrees)` 每次调用都会先将自身重置为单位矩阵,因此原 `ImageHelper` 中对同一 `hueMatrix` 连续调用 `setRotate(0, hue); setRotate(1, hue); setRotate(2, hue);` 实际只有最后一次 `axis=2` 生效;若要三轴叠加旋转应使用三个独立矩阵并通过 `postConcat` 相乘。源示例包 `ColorMatrixDemo.zip` 与 `ColorMatrixDemo2.zip` 均因停采策略未下载并已登记。

验证 4×5 ColorMatrix 仿射像素数学、setSaturation/setScale/postConcat 与 SeekBar 映射

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对单位矩阵、蓝通道×2、怀旧 Sepia、去饱和度灰度(118)经 postConcat 半亮至(59)及 SeekBar 0/127/255 映射。
验证 4×5 ColorMatrix 仿射像素数学、setSaturation/setScale/postConcat 与 SeekBar 映射

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

当前源码 SHA256:dd04c7ab17505cb3efbab077d0d067062193efecd4f77e82eba307ebf8aaced9

下载本站示例源码

本地运行

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

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

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

ZIP SHA256:40a9322787c658e81795c014a4286a36888238d155612d7086f0e21ee16ecf79

常见错误与边界

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

练习与解答

在 ColorMatrix 中,为什么对同一个 ColorMatrix 对象连续调用 setRotate(0, hue)、setRotate(1, hue)、setRotate(2, hue) 不会叠加三次旋转?

展开参考解答

ColorMatrix.setRotate() 内部会先将矩阵重置为单位矩阵再写入该轴的旋转系数,后续调用会覆盖前一次结果;如需组合多轴旋转应分别构造矩阵并用 postConcat() 串联相乘。

规范与官方依据