蓝色天空.知识 · 实践 · 创造
我的收藏
Android 教程目录 156章
课程介绍
Android / LEARN BY DOING

8.3.6 Paint API 之—— Xfermode 与 PorterDuff 详解(三)

实战演练利用 PorterDuff.Mode.DST_IN 定制支持圆形与圆角两种模式的 CircleImageView,剖析自定义属性、等比缩放测量、离屏遮罩及 WeakReference 缓存细节。

学完这一章,你能够

  • 实战演练利用 PorterDuff.Mode.DST_IN 定制支持圆形与圆角两种模式的 CircleImageView,剖析自定义属性、等比缩放测量、离屏遮罩及 WeakReference 缓存细节。

DST_IN 裁剪原理与自定义 CircleImageView 流程

相较于前文通过 `canvas.clipPath()` 切圆容易产生边缘锯齿,利用 `PorterDuff.Mode.DST_IN` 可高质量实现抗锯齿的圆形与圆角 `ImageView`。其两层绘制顺序非常清晰:先将待展示的原图绘制到离屏缓冲 `Bitmap` 上作为目标图(DST),再启用 `DST_IN` 并将纯色抗锯齿圆形或圆角矩形遮罩作为源图(SRC)绘制其上;由于 `DST_IN` 的结果方程为 `[Sa·Da, Sa·Dc]`,仅在遮罩不透明的相交区域保留原图,遮罩外的像素全部变为透明,边缘过渡亦自动继承遮罩抗锯齿 Alpha。整体工程分为四步:定义自定义属性 `attrs.xml`、在 `onMeasure()` 对圆形模式按 `min(width, height)` 强制正方形、在 `onDraw()` 按最大边比缩放图片并执行 `DST_IN` 混合,以及用 `WeakReference<Bitmap>` 缓存合成结果避免每帧重复分配内存。

自定义属性、源码剖析与缓存回收缺陷修正

在 `res/values/attrs.xml` 中为 `CircleImageView` 声明 `Radius`(`dimension`)与 `type`(枚举 `circle=0`、`round=1`),布局文件借助 `xmlns:app="http://schemas.android.com/apk/res-auto"` 分别配置圆形与 `30dp` 圆角实例。`CircleImageView` 构造中通过 `TypedArray` 读取属性并记得 `recycle()`;`onDraw()` 中对 `TYPE_ROUND` 取 `max(vw/dw, vh/dh)`、对 `TYPE_CIRCLE` 取 `vw / min(dw, dh)` 计算缩放系数以保证图片填满视图。核对源码时需特别留意两处细节:第一,三参构造应委托二参构造或同样解析属性;第二,示例 `invalidate()` 中先写了 `mWeakBitmap = null;` 再判断 `if (mWeakBitmap != null)`,导致分支内 `mMaskBitmap.recycle()` 成为永不执行的死代码,正确写法应直接判断 `if (mMaskBitmap != null)` 后回收置空。源示例包 `XfermodeDemo1.zip` 因停采策略未联网下载并已登记。

验证 DST_IN 圆形/圆角遮罩像素混合、CircleImageView 缩放计算与 invalidate() 缺陷检测

含完整源码 · 164 行
展开查看收起
python
"""Offline verification lab for Android Ch 115: tutorial-xfermode-porterduff3."""
import json
import xml.etree.ElementTree as ET

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

ATTRS_XML = """<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CircleImageView">
        <attr name="Radius" format="dimension"/>
        <attr name="type">
            <enum name="circle" value="0"/>
            <enum name="round" value="1"/>
        </attr>
    </declare-styleable>
</resources>"""

LAYOUT_XML = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
    <com.jay.xfermodedemo1.CircleImageView android:layout_width="160dp" android:layout_height="240dp"
        android:layout_margin="10dp" android:src="@mipmap/ic_bg_2" app:type="circle" />
    <com.jay.xfermodedemo1.CircleImageView android:layout_width="160dp" android:layout_height="280dp"
        android:layout_margin="10dp" android:src="@mipmap/ic_bg_1" app:Radius="30dp" app:type="round" />
</LinearLayout>"""


def dst_in(src_a: float, dst_argb):
    da, dr, dg, db = [c / 255.0 for c in dst_argb]
    out_a = da * src_a
    if out_a <= 1e-9:
        return [0, 0, 0, 0]
    # Premultiplied dst_c * src_a, unpremultiplied = (da*c*src_a)/(da*src_a) = c
    return [round(out_a * 255), dst_argb[1], dst_argb[2], dst_argb[3]]


def case_dst_in_circle_and_roundrect_mask_pixels():
    img_px = [255, 64, 180, 220]
    inside = dst_in(1.0, img_px)
    outside = dst_in(0.0, img_px)
    antialiased_edge = dst_in(0.5, img_px)
    actual = {
        "inside_mask_keeps_dst": inside,
        "outside_mask_cleared": outside,
        "edge_half_alpha_preserves_rgb": antialiased_edge,
    }
    expected = {
        "inside_mask_keeps_dst": [255, 64, 180, 220],
        "outside_mask_cleared": [0, 0, 0, 0],
        "edge_half_alpha_preserves_rgb": [128, 64, 180, 220],
    }
    return {
        "name": "dst_in_circle_and_roundrect_mask_pixels",
        "summary": "Verify PorterDuff.Mode.DST_IN keeps DST image inside mask and clears exterior",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_circle_imageview_measure_and_scale_math():
    # Circle: 160x240 -> min(160, 240) = 160x160; drawable 320x480 -> scale = 160 / min(320, 480) = 0.5
    circle_side = min(160, 240)
    circle_scale = circle_side / min(320, 480)
    circle_bounds = [0, 0, int(circle_scale * 320), int(circle_scale * 480)]
    # Round: 160x280, drawable 400x200 -> max(160/400, 280/200) = max(0.4, 1.4) = 1.4
    round_scale = max(160.0 / 400.0, 280.0 / 200.0)
    round_bounds = [0, 0, int(round_scale * 400), int(round_scale * 200)]
    actual = {
        "circle_measured_size": [circle_side, circle_side],
        "circle_scale": circle_scale,
        "circle_drawable_bounds": circle_bounds,
        "round_scale": round_scale,
        "round_drawable_bounds": round_bounds,
    }
    expected = {
        "circle_measured_size": [160, 160],
        "circle_scale": 0.5,
        "circle_drawable_bounds": [0, 0, 160, 240],
        "round_scale": 1.4,
        "round_drawable_bounds": [0, 0, 560, 280],
    }
    return {
        "name": "circle_imageview_measure_and_scale_math",
        "summary": "Verify CircleImageView onMeasure min clamping and circle/round scale-to-fill bounds",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_custom_attrs_and_layout_xml_parsing():
    aroot = ET.fromstring(ATTRS_XML)
    styleable = aroot.find("declare-styleable")
    enums = {e.attrib["name"]: int(e.attrib["value"]) for e in styleable.findall(".//enum")}
    lroot = ET.fromstring(LAYOUT_XML)
    app_ns = "{http://schemas.android.com/apk/res-auto}"
    views = list(lroot)
    actual = {
        "styleable_name": styleable.attrib["name"],
        "type_enums": enums,
        "view_types": [v.attrib[app_ns + "type"] for v in views],
        "round_radius_attr": views[1].attrib[app_ns + "Radius"],
    }
    expected = {
        "styleable_name": "CircleImageView",
        "type_enums": {"circle": 0, "round": 1},
        "view_types": ["circle", "round"],
        "round_radius_attr": "30dp",
    }
    return {
        "name": "custom_attrs_and_layout_xml_parsing",
        "summary": "Verify declare-styleable CircleImageView custom attrs and layout XML bindings",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_weakreference_cache_and_invalidate_bug_check():
    # Source bug: mWeakBitmap = null; if (mWeakBitmap != null) { mMaskBitmap.recycle(); }
    mask_recycled_buggy = False
    weak_ref = "cached_bitmap"
    weak_ref = None
    if weak_ref is not None:
        mask_recycled_buggy = True

    # Fixed order: check mMaskBitmap != null directly
    mask_bitmap = "mask_bmp"
    mask_recycled_fixed = False
    if mask_bitmap is not None:
        mask_recycled_fixed = True
        mask_bitmap = None

    actual = {
        "source_invalidate_dead_branch_skips_recycle": not mask_recycled_buggy,
        "fixed_invalidate_recycles_mask": mask_recycled_fixed and mask_bitmap is None,
    }
    expected = {
        "source_invalidate_dead_branch_skips_recycle": True,
        "fixed_invalidate_recycles_mask": True,
    }
    return {
        "name": "weakreference_cache_and_invalidate_bug_check",
        "summary": "Detect dead null-check bug in source invalidate() and verify corrected mMaskBitmap recycle",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_dst_in_circle_and_roundrect_mask_pixels(),
        case_circle_imageview_measure_and_scale_math(),
        case_custom_attrs_and_layout_xml_parsing(),
        case_weakreference_cache_and_invalidate_bug_check(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对遮罩内保留原图/外透明/半透明边缘保留 RGB、160x240 圆形裁剪至 160x160 及修正后 mMaskBitmap 回收。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a1829.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

示例中先画原图(DST)再画遮罩(SRC),需要在相交区域保留先画的 DST 图像,因此选用 DST_IN;若反过来先画遮罩(DST)再画原图(SRC),则应在相交区域保留后画的 SRC 图像,需改用 SRC_IN。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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