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

8.3.4 Paint API 之—— Xfermode 与 PorterDuff 详解(一)

梳理 Xfermode 三个子类的继承体系,解析已于 API 16 废弃的 AvoidXfermode(TARGET/AVOID 与容差)与 PixelXorXfermode 异或算法及历史迁移背景。

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

学完这一章,你能够

Xfermode 体系概览与 AvoidXfermode 两种模式

`Paint.setXfermode(Xfermode)` 用于定义源图形(SRC)与画布已有目标图形(DST)重叠时的像素混合规则,是实现圆角头像、橡皮擦除与遮罩特效的核心接口。Android 早期官方文档列出三个子类:`AvoidXfermode`、`PixelXorXfermode` 与 `PorterDuffXfermode`(官方 ApiDemos 的 `Xfermodes.java` 即用于演示混合模式)。本节先剖析前两个历史子类,下节起深入主力 `PorterDuffXfermode`。

`AvoidXfermode(int opColor, int tolerance, AvoidXfermode.Mode mode)` 同样不支持硬件加速,需关闭硬件加速后生效。其三项参数依次为:参考色 `opColor`、容差值 `tolerance`(范围 `0–255`,类似魔棒取色宽容度)与模式 `mode`(`TARGET` 或 `AVOID`)。在 `Mode.TARGET` 下,画布中与 `opColor` 相同或在容差范围内的像素会被画笔新颜色替换(注意原文首句误笔写作“不一样”,后续解释与实测均为“颜色一致/接近才染色”),例如用 `0xFFCCD1D4` 配合容差 `0` 精确替换墙面色,或用 `0xFFD9E5F3` 配合容差 `25` 扩大到相近浅色区域;而在 `Mode.AVOID` 下行为相反,与 `opColor` 差异越大的像素越会被染色,容差越大允许的避开范围越窄(例如容差 `230` 仅保护非常接近 `opColor` 的像素,其余区域均被染色)。

PixelXorXfermode 异或算法与 API 16 废弃说明

`PixelXorXfermode(int opColor)` 仅接受一个基准颜色值,对重叠像素按位执行 `opColor ^ src ^ dst` 运算,并将输出 Alpha 强制置为不透明 `255`(`0xFF`),从而产生反色与高对比度色彩错位效果。需要明确历史迁移背景:`AvoidXfermode` 与 `PixelXorXfermode` 均早在 Android 4.1(API 16)即被官方标记废弃(且在现代硬件加速管线中不可用),了解其像素容差与按位异或思路有助于读懂遗留代码,而现代 Android 自定义绘图应统一采用下一节的 `PorterDuffXfermode`(或 API 29+ 的 `BlendMode`)。源示例包 `XfermodeDemo.zip` 因停采限制未联网抓取并已登记。

验证 AvoidXfermode TARGET/AVOID 容差染色与 PixelXorXfermode 位异或公式

python · 阅读源码
"""Offline verification lab for Android Ch 113: tutorial-xfermode-porterduff."""
import json

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


def split_argb(c: int):
    return ((c >> 24) & 0xFF, (c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF)


def rgb_max_diff(c1: int, c2: int) -> int:
    _, r1, g1, b1 = split_argb(c1)
    _, r2, g2, b2 = split_argb(c2)
    return max(abs(r1 - r2), abs(g1 - g2), abs(b1 - b2))


def apply_avoid_xfermode(dst: int, src: int, op_color: int, tolerance: int, mode: str) -> int:
    diff = rgb_max_diff(dst, op_color)
    if mode == "TARGET":
        return src if diff <= tolerance else dst
    elif mode == "AVOID":
        return src if diff > (255 - tolerance) else dst
    raise ValueError(mode)


def apply_pixel_xor(dst: int, src: int, op_color: int) -> int:
    return ((op_color ^ src ^ dst) & 0x00FFFFFF) | 0xFF000000


def case_avoid_xfermode_target_mode_tolerance():
    paint_red = 0xFFDE5347  # ARGB(255, 222, 83, 71)
    # Exact match with tolerance=0
    exact_hit = apply_avoid_xfermode(0xFFCCD1D4, paint_red, 0xFFCCD1D4, 0, "TARGET")
    exact_miss = apply_avoid_xfermode(0xFFCCD1D5, paint_red, 0xFFCCD1D4, 0, "TARGET")
    # Tolerance=25 around 0xFFD9E5F3
    near_hit = apply_avoid_xfermode(0xFFC8DCF0, paint_red, 0xFFD9E5F3, 25, "TARGET")
    far_miss = apply_avoid_xfermode(0xFF90A0B0, paint_red, 0xFFD9E5F3, 25, "TARGET")
    actual = {
        "tol0_exact_match_tinted": f"0x{exact_hit:08X}",
        "tol0_off_by_1_preserved": f"0x{exact_miss:08X}",
        "tol25_within_range_tinted": f"0x{near_hit:08X}",
        "tol25_far_color_preserved": f"0x{far_miss:08X}",
    }
    expected = {
        "tol0_exact_match_tinted": "0xFFDE5347",
        "tol0_off_by_1_preserved": "0xFFCCD1D5",
        "tol25_within_range_tinted": "0xFFDE5347",
        "tol25_far_color_preserved": "0xFF90A0B0",
    }
    return {
        "name": "avoid_xfermode_target_mode_tolerance",
        "summary": "Verify AvoidXfermode.Mode.TARGET exact (tol=0) and tolerance=25 color matching",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_avoid_xfermode_avoid_mode_tolerance():
    paint_red = 0xFFDE5347
    op_color = 0xFFD9E5F3
    # With AVOID and tolerance=230, threshold = 255 - 230 = 25 -> diff > 25 gets tinted, diff <= 25 protected
    protected = apply_avoid_xfermode(0xFFD9E5F3, paint_red, op_color, 230, "AVOID")
    tinted = apply_avoid_xfermode(0xFF404040, paint_red, op_color, 230, "AVOID")
    actual = {
        "matching_pixel_protected": f"0x{protected:08X}",
        "different_pixel_tinted": f"0x{tinted:08X}",
    }
    expected = {
        "matching_pixel_protected": "0xFFD9E5F3",
        "different_pixel_tinted": "0xFFDE5347",
    }
    return {
        "name": "avoid_xfermode_avoid_mode_tolerance",
        "summary": "Verify AvoidXfermode.Mode.AVOID protects opColor while tinting dissimilar pixels",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_pixel_xor_xfermode_bitwise_formula():
    op_color = 0xFFD9E5F3
    src = 0xFFDE5347
    dst = 0xFF336699
    res = apply_pixel_xor(dst, src, op_color)
    a, r, g, b = split_argb(res)
    actual = {
        "result_hex": f"0x{res:08X}",
        "alpha_forced_255": a,
        "rgb": [r, g, b],
    }
    expected = {
        "result_hex": "0xFF34D02D",
        "alpha_forced_255": 255,
        "rgb": [0x34, 0xD0, 0x2D],
    }
    return {
        "name": "pixel_xor_xfermode_bitwise_formula",
        "summary": "Verify PixelXorXfermode bitwise (opColor ^ src ^ dst) with opaque alpha=255",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_api16_deprecation_and_hardware_accel_notice():
    deprecated_in_api = 16
    actual = {
        "avoid_and_pixelxor_deprecated_api": deprecated_in_api,
        "hardware_accelerated_supported": False,
        "recommended_replacement": "PorterDuffXfermode",
    }
    expected = {
        "avoid_and_pixelxor_deprecated_api": 16,
        "hardware_accelerated_supported": False,
        "recommended_replacement": "PorterDuffXfermode",
    }
    return {
        "name": "api16_deprecation_and_hardware_accel_notice",
        "summary": "Verify API 16 deprecation status of AvoidXfermode & PixelXorXfermode and PorterDuffXfermode replacement",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_avoid_xfermode_target_mode_tolerance(),
        case_avoid_xfermode_avoid_mode_tolerance(),
        case_pixel_xor_xfermode_bitwise_formula(),
        case_api16_deprecation_and_hardware_accel_notice(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 tol=0 精确命中、tol=25 容差放宽、AVOID tol=230 保护参考色及 0xFFD9E5F3 ^ 0xFFDE5347 ^ 0xFF336699 = 0xFF34D02D。
验证 AvoidXfermode TARGET/AVOID 容差染色与 PixelXorXfermode 位异或公式

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

当前源码 SHA256:57074af62125f5e8730d4763cdc3dc6ecc20fffe10a2933a3669ef4a1ebcfc0d

下载本站示例源码

本地运行

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

下载8.3.4 Paint API 之—— Xfermode 与 PorterDuff 详解(一)实验

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

ZIP SHA256:5987534bf4ee5c37fdbb9bb50fa08aa56e1ba7ba65c61e388081541065d31323

常见错误与边界

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

练习与解答

AvoidXfermode.Mode.TARGET 与 AVOID 两种模式在像素筛选上有什么区别?这两个类为何不建议在新项目中使用?

展开参考解答

TARGET 只对与 opColor 一致或在容差范围内的像素染色,AVOID 则保护与 opColor 接近的像素而对其余像素染色;AvoidXfermode 与 PixelXorXfermode 均不支持硬件加速且已于 API 16 废弃,新项目应改用 PorterDuffXfermode 或 BlendMode。

规范与官方依据