8.3.17 Canvas API详解(Part 2)剪切方法合集
核对 Android Canvas 的 clipRect、clipPath、clipRegion 三类画布裁剪方法,完整求解 Region.Op 六种集合运算、百叶窗 Region.union 动画、变换矩阵影响差异及 API 26/28 裁剪限制。
学完这一章,你能够
- 核对 Android Canvas 的 clipRect、clipPath、clipRegion 三类画布裁剪方法,完整求解 Region.Op 六种集合运算、百叶窗 Region.union 动画、变换矩阵影响差异及 API 26/28 裁剪限制。
Canvas 裁剪机制与 Region.Op 六种集合运算
`Canvas` 提供 `clipRect()`、`clipPath()` 与 `clipRegion()` 三类裁剪方法,分别基于矩形(`Rect`/`RectF`)、任意开放/闭合路径(`Path`)与封闭区域集合(`Region`)限定可见绘制范围。必须牢记:`Canvas` 的裁剪操作作用于**后续绘制的画布区域**,对已经画出的内容不产生回溯影响。当先后裁剪区域 `A` 与 `B` 时,`Region.Op` 定义了六种布尔运算:`DIFFERENCE`(差集 `A - B`)、`INTERSECT`(交集 `A ∩ B`)、`UNION`(并集 `A ∪ B`)、`XOR`(异或/对称差 `(A ∪ B) - (A ∩ B)`,纠偏原文首处“A 除去 B”的口误)、`REVERSE_DIFFERENCE`(反向差集 `B - A`)与 `REPLACE`(完全以 `B` 取代 `A`)。
对 `A = (10, 10, 110, 110)` 与 `B = (50, 50, 150, 150)` 两个 `100×100` 矩形(相交区 `60×60 = 3600px²`),本站离线网格逐像素核验了全部六种 `Region.Op` 的精确可见面积:`DIFFERENCE` 与 `REVERSE_DIFFERENCE` 均为 `6400px²`、`INTERSECT` 为 `3600px²`、`UNION` 为 `16400px²`、`XOR` 为 `12800px²`、`REPLACE` 为 `10000px²`(注:原文 `UNION` 代码段将第二个矩形写成 `(40,40,140,140)`,文字说明按 `(50,50)` 统一口径)。
百叶窗 Region.union 实战与 clipRect 矩阵联动
借助 `Region.union(Rect)` 可以构建横向交替收展的百叶窗动画:以条带高度 `CLIP_HEIGHT = 50` 遍历图片高度,偶数条带从左边缘 `[0, limitLength]` 展开、奇数条带从右边缘 `[width - limitLength, width]` 展开,每帧按 `HIDE`(每次 `-10`)与 `SHOW`(每次 `+5`)交替更新 `limitLength` 并触发 `invalidate()`。需特别注意:`Canvas` 的矩阵变换(如 `translate`/`rotate`)对 `clipRegion` **不生效**,且 `clipRegion()` 已在 Android 8.0(API 26)起废弃。
`clipRect` 拥有七个重载方法,支持传入 `Rect`/`RectF` 或四个整型/浮点边界 `(left, top, right, bottom)` 及可选的 `Region.Op`。与 `clipRegion` 不同,`clipRect` 会严格受 `Canvas` 当前矩阵变换影响:先 `translate(300, 300)` 再 `clipRect(100, 100, 300, 300)` 时,实际屏幕裁剪框位于 `[400, 400, 600, 600]`,随后调用 `drawColor(WHITE)` 与 `drawText(...)` 仅在该裁剪矩形内可见,越界文字自动截断。
clipPath 圆形头像示例与 API 28 裁剪限制
`clipPath` 只需构造 `Path` 后裁剪画布即可切出任意轮廓,例如自定义 `RoundImageView` 在 `onDraw()` 中添加圆形路径裁剪后再绘制位图。但直接用 `clipPath` 存在三点工程局限:一是边缘锯齿明显,即使开启 `Paint` 抗锯齿或 `PaintFlagsDrawFilter` 仍难彻底消除,高质量圆角/圆形头像应改用 `Xfermode`、`BitmapShader` 或 Material 的 `ShapeableImageView`;二是示例代码中 `mPath.addCircle(getWidth()/2, getWidth()/2, getHeight()/2, ...)` 在非正方形控件下圆心纵坐标有误且未调用 `mPath.reset()`,应修正为 `(getWidth()/2f, getHeight()/2f, Math.min(getWidth(), getHeight())/2f)`;三是 Android 9(API 28)起已废弃并禁止扩展类 `Region.Op`(仅保留收缩交集 `clipRect`/`clipPath` 与差集 `clipOutRect`/`clipOutPath`)。来源页面附带的 `CanvasDemo2.zip` 与 `XfermodeDemo1.zip` 因继承停采策略未联网下载,已分别登记留痕。
运行离线 Region.Op 六种集合面积、百叶窗条带、clipRect 矩阵影响及 API 28 裁剪限制核验
"""Offline Android graphics verifier for Ch 126: Canvas Clipping & Region.Op."""
from dataclasses import dataclass
import json
VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"
@dataclass(frozen=True)
class Rect:
left: int
top: int
right: int
bottom: int
def contains(self, x: int, y: int) -> bool:
return self.left <= x < self.right and self.top <= y < self.bottom
def eval_region_op(a: Rect, b: Rect, op: str, grid_size: int = 200) -> int:
# Count integer pixel area inside [0, grid_size) x [0, grid_size)
area = 0
for x in range(grid_size):
for y in range(grid_size):
in_a = a.contains(x, y)
in_b = b.contains(x, y)
if op == "DIFFERENCE":
keep = in_a and not in_b
elif op == "INTERSECT":
keep = in_a and in_b
elif op == "UNION":
keep = in_a or in_b
elif op == "XOR":
keep = in_a != in_b
elif op == "REVERSE_DIFFERENCE":
keep = in_b and not in_a
elif op == "REPLACE":
keep = in_b
else:
raise ValueError(op)
if keep:
area += 1
return area
def blinds_region_area(width: int, height: int, clip_height: int, limit_len: int) -> tuple[int, int]:
strips = 0
area = 0
i = 0
while i * clip_height <= height:
top = i * clip_height
bottom = min((i + 1) * clip_height, height)
if bottom > top:
strips += 1
area += max(0, min(width, limit_len)) * (bottom - top)
i += 1
return strips, area
def main() -> None:
# Case 1: All 6 Region.Op set operations on A=(10,10,110,110) and B=(50,50,150,150)
# |A|=10000, |B|=10000, |A∩B|=60*60=3600
a = Rect(10, 10, 110, 110)
b = Rect(50, 50, 150, 150)
ops = ("DIFFERENCE", "INTERSECT", "UNION", "XOR", "REVERSE_DIFFERENCE", "REPLACE")
c1_actual = {op: eval_region_op(a, b, op, 200) for op in ops}
c1_expected = {
"DIFFERENCE": 6400,
"INTERSECT": 3600,
"UNION": 16400,
"XOR": 12800,
"REVERSE_DIFFERENCE": 6400,
"REPLACE": 10000,
}
# Case 2: Blinds effect (CLIP_HEIGHT=50, 200x200 bitmap): HIDE (-10/step) -> SHOW (+5/step)
strips_full, area_full = blinds_region_area(200, 200, 50, 200)
strips_half, area_half = blinds_region_area(200, 200, 50, 100)
# Transition steps from 200 -> 0 by -10 takes 20 steps; 0 -> 200 by +5 takes 40 steps
c2_actual = {
"strip_count": strips_full,
"area_at_limit_200": area_full,
"area_at_limit_100": area_half,
"hide_steps": 200 // 10,
"show_steps": 200 // 5,
}
c2_expected = {
"strip_count": 4,
"area_at_limit_200": 40000,
"area_at_limit_100": 20000,
"hide_steps": 20,
"show_steps": 40,
}
# Case 3: clipRect affected by Canvas.translate(300,300) vs clipRegion unaffected
# Local clipRect(100,100,300,300) after translate(300,300) -> screen [400,400,600,600]
tx, ty = 300, 300
clip_rect_screen = [100 + tx, 100 + ty, 300 + tx, 300 + ty]
clip_region_screen = [100, 100, 300, 300]
c3_actual = {
"clipRect_screen_bounds": clip_rect_screen,
"clipRegion_screen_bounds": clip_region_screen,
"clipRect_affected_by_matrix": clip_rect_screen != clip_region_screen,
}
c3_expected = {
"clipRect_screen_bounds": [400, 400, 600, 600],
"clipRegion_screen_bounds": [100, 100, 300, 300],
"clipRect_affected_by_matrix": True,
}
# Case 4: RoundImageView clipPath geometry fix on 300x200 view & API 28 Region.Op restriction
w, h = 300, 200
buggy_circle = [w // 2, w // 2, h // 2]
fixed_circle = [w // 2, h // 2, min(w, h) // 2]
api28_allowed_ops = ["INTERSECT", "DIFFERENCE"]
c4_actual = {
"buggy_non_square_circle_cx_cy_r": buggy_circle,
"fixed_non_square_circle_cx_cy_r": fixed_circle,
"api28_supported_clip_ops": api28_allowed_ops,
}
c4_expected = {
"buggy_non_square_circle_cx_cy_r": [150, 150, 100],
"fixed_non_square_circle_cx_cy_r": [150, 100, 100],
"api28_supported_clip_ops": ["INTERSECT", "DIFFERENCE"],
}
cases = [
{
"name": "region_op_six_set_operations",
"summary": "核验 Region.Op 六种集合裁剪运算在 A(10,10,110,110) 与 B(50,50,150,150) 上的精确像素面积",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "region_union_blinds_animation",
"summary": "核验百叶窗 Region.union 交替条带数量、面积变化及 HIDE(-10)/SHOW(+5) 状态步数",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "cliprect_vs_clipregion_transform_matrix",
"summary": "核验 translate(300,300) 对 clipRect 生效而对 clipRegion 不生效的屏幕坐标差异",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "round_imageview_clippath_and_api28_ops",
"summary": "核验 RoundImageView 非正方形圆心偏移纠偏及 API 28 后仅保留 INTERSECT/DIFFERENCE 的限制",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 验证六种 Region.Op 像素面积、200x200 百叶窗 4 条带与步数、translate 对 clipRect/clipRegion 的差异及非正方形圆心修正。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:6957e49fd0485a447297f3bfbabf44b0d438870115d1fa46dbb003768516fa0a
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:716a435dacbc88d2d22f08099304d41023ccf45ed9bd7dfb3ff2c8f4a974dcf7
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Android 9(API 28)及更高版本中,`canvas.clipPath(path, Region.Op.REPLACE)` 为何会抛出异常?应改用哪些官方方法?
展开参考解答
API 28 起系统移除了会扩大当前裁剪区的 `Region.Op`(如 `UNION`、`XOR`、`REVERSE_DIFFERENCE`、`REPLACE`);现代代码仅可使用默认交集裁剪 `clipRect()`/`clipPath()` 或差集挖空裁剪 `clipOutRect()`/`clipOutPath()`。