8.3.12 Paint API之—— PathEffect(路径效果)
核对 Android Paint.setPathEffect 的六大 PathEffect 子类(CornerPathEffect、DashPathEffect、DiscretePathEffect、PathDashPathEffect、ComposePathEffect、SumPathEffect)的构造参数、组合顺序与相位平移动画机制。
学完这一章,你能够
- 核对 Android Paint.setPathEffect 的六大 PathEffect 子类(CornerPathEffect、DashPathEffect、DiscretePathEffect、PathDashPathEffect、ComposePathEffect、SumPathEffect)的构造参数、组合顺序与相位平移动画机制。
PathEffect 定位与六大子类概览
当把 `Paint` 的样式设为描边(`Paint.Style.STROKE`)绘制折线或多边形路径时,默认连续实线往往缺乏变化。借助 `Paint.setPathEffect(PathEffect)` 可以为路径施加圆角转折、虚线、离散抖动或图形印章等描边特效。与 `MaskFilter`、`ColorFilter` 类似,`PathEffect` 基类本身不暴露业务方法,开发中直接使用其六个子类:`CornerPathEffect`、`DashPathEffect`、`DiscretePathEffect`、`PathDashPathEffect`、`ComposePathEffect` 与 `SumPathEffect`。
六大子类的作用机制与构造参数
前三个子类分别处理几何平滑、虚线与分段扰动:`CornerPathEffect(float radius)` 用指定半径 `radius` 的切线圆弧替代折线夹角(本站实验核验 `radius=10` 在 90° 与 60° 夹角处的切线回退距离分别为 `10.0` 与 `17.3205`);`DashPathEffect(float[] intervals, float phase)` 按交替的实线/空白(ON/OFF)长度数组把路径虚线化,要求数组长度 `>= 2` 且为偶数(奇数长度非法),`phase` 指定起始相位偏移;`DiscretePathEffect(float segmentLength, float deviation)` 则按最大分段长度 `segmentLength` 将路径打散,并对各分段顶点施加不超过 `deviation` 的随机偏移(`40px` 边长按 `segmentLength=3.0` 拆分为 `14` 段)。
后三个子类负责自定义图元印章与双效果合成:`PathDashPathEffect(Path shape, float advance, float phase, PathDashPathEffect.Style style)` 使用自定义 `Path` 图形 `shape` 以间距 `advance` 与相位 `phase` 沿路径平铺,其连接风格支持 `ROTATE`(随下一段方向旋转图元)、`MORPH`(在转折处拉伸压缩变形衔接)与 `TRANSLATE`(仅平移不旋转);`ComposePathEffect(PathEffect outerpe, PathEffect innerpe)` 按“先内后外”顺序链式组合,先对原始路径应用 `innerpe`,再把 `outerpe` 施加于其结果之上;`SumPathEffect(PathEffect first, PathEffect second)` 则是平行叠加,把两个独立作用后的路径直接重叠绘制在一起。
PathEffectView 动画实现与工程注意事项
自定义视图 `PathEffectView` 在 `init()` 中构造一条 15 段随机折线并设置抗锯齿 `STROKE` 画笔,随后在 `onDraw()` 中以 7 种颜色依次绘制无效果与六种 `PathEffect`,每次纵向平移 `60px` 并将 `phase += 2` 后调用 `invalidate()` 驱动虚线与印章沿路径流动。需提醒工程细节:参考代码在 `onDraw()` 中每次重绘都 `new` 全部 `PathEffect` 与 `Path` 对象,高帧率刷新易引发频繁 GC 抖动,生产实践应将不依赖 `phase` 的对象预分配为成员变量,仅在 `phase` 变化时重建对应实例。来源页面附带的工程包 `PathEffectDemo.zip` 因继承的源站停采策略未联网下载,已单独登记留痕。
运行离线 PathEffect 虚线相位、圆角切线、PathDash 印章与 Compose/Sum 顺序核验
"""Offline Android graphics verifier for Ch 121: Paint PathEffect."""
from dataclasses import dataclass
import json
import math
VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"
def dash_segments(total_len: float, intervals: list[float], phase: float) -> list[tuple[float, float]]:
if len(intervals) < 2 or len(intervals) % 2 != 0:
raise ValueError("DashPathEffect requires an even number of intervals >= 2")
period = sum(intervals)
offset = phase % period
# Locate starting interval at offset
idx = 0
rem = offset
while rem >= intervals[idx]:
rem -= intervals[idx]
idx = (idx + 1) % len(intervals)
pos = 0.0
out: list[tuple[float, float]] = []
first_span = intervals[idx] - rem
while pos < total_len - 1e-9:
span = first_span if first_span is not None else intervals[idx]
first_span = None
end = min(total_len, pos + span)
if idx % 2 == 0 and end > pos:
out.append((round(pos, 3), round(end, 3)))
pos = end
idx = (idx + 1) % len(intervals)
return out
def corner_fillet_tangent(radius: float, interior_deg: float) -> tuple[float, float]:
# Distance from corner vertex to tangent point along each edge: r / tan(theta/2)
half_rad = math.radians(interior_deg / 2.0)
tangent_dist = radius / math.tan(half_rad)
arc_len = radius * (math.pi - math.radians(interior_deg))
return round(tangent_dist, 4), round(arc_len, 4)
def path_dash_stamps(path_len: float, advance: float, phase: float, style: str) -> dict:
valid_styles = ("ROTATE", "MORPH", "TRANSLATE")
if style not in valid_styles:
raise ValueError(f"Unknown PathDashPathEffect.Style: {style}")
start = (-phase) % advance
positions = []
pos = start
while pos <= path_len + 1e-9:
positions.append(round(pos, 2))
pos += advance
return {"style": style, "count": len(positions), "positions": positions}
@dataclass(frozen=True)
class EffectSpec:
kind: str
params: tuple
def apply_effect_order(kind: str, a: str, b: str) -> list[str]:
if kind == "ComposePathEffect":
# ComposePathEffect(outerpe, innerpe): applies innerpe first, then outerpe
return [f"stage1:{b}", f"stage2:{a}(on {b})"]
if kind == "SumPathEffect":
# SumPathEffect(first, second): renders both independently and overlays
return [f"layer_a:{a}", f"layer_b:{b}"]
raise ValueError(kind)
def main() -> None:
# Case 1: DashPathEffect(intervals=[20, 10, 5, 10], phase=0 vs phase=12)
segs_p0 = dash_segments(60.0, [20.0, 10.0, 5.0, 10.0], 0.0)
segs_p12 = dash_segments(60.0, [20.0, 10.0, 5.0, 10.0], 12.0)
odd_rejected = False
try:
dash_segments(60.0, [20.0, 10.0, 5.0], 0.0)
except ValueError:
odd_rejected = True
c1_actual = {
"phase_0_on_segments": [list(s) for s in segs_p0],
"phase_12_on_segments": [list(s) for s in segs_p12],
"odd_interval_rejected": odd_rejected,
}
c1_expected = {
"phase_0_on_segments": [[0.0, 20.0], [30.0, 35.0], [45.0, 60.0]],
"phase_12_on_segments": [[0.0, 8.0], [18.0, 23.0], [33.0, 53.0]],
"odd_interval_rejected": True,
}
# Case 2: CornerPathEffect(10) on 90-degree & 60-degree vertices + DiscretePathEffect subdivision
tan90, arc90 = corner_fillet_tangent(10.0, 90.0)
tan60, arc60 = corner_fillet_tangent(10.0, 60.0)
# DiscretePathEffect(segmentLength=3.0, deviation=5.0) on a 40px edge -> ceil(40/3) = 14 sub-segments
discrete_segs = math.ceil(40.0 / 3.0)
c2_actual = {
"corner_90_tangent_arc": [tan90, arc90],
"corner_60_tangent_arc": [tan60, arc60],
"discrete_subsegments_on_40px": discrete_segs,
"max_perpendicular_deviation": 5.0,
}
c2_expected = {
"corner_90_tangent_arc": [10.0, 15.708],
"corner_60_tangent_arc": [17.3205, 20.944],
"discrete_subsegments_on_40px": 14,
"max_perpendicular_deviation": 5.0,
}
# Case 3: PathDashPathEffect(rect 8x8, advance=12, phase=0/2/4, ROTATE/MORPH/TRANSLATE)
stamps_p0 = path_dash_stamps(40.0, 12.0, 0.0, "ROTATE")
stamps_p2 = path_dash_stamps(40.0, 12.0, 2.0, "ROTATE")
styles = [path_dash_stamps(24.0, 12.0, 0.0, s)["style"] for s in ("ROTATE", "MORPH", "TRANSLATE")]
c3_actual = {
"phase_0_positions": stamps_p0["positions"],
"phase_2_positions": stamps_p2["positions"],
"supported_styles": styles,
}
c3_expected = {
"phase_0_positions": [0.0, 12.0, 24.0, 36.0],
"phase_2_positions": [10.0, 22.0, 34.0],
"supported_styles": ["ROTATE", "MORPH", "TRANSLATE"],
}
# Case 4: ComposePathEffect vs SumPathEffect + PathEffectView 7-row layout & phase animation
compose_flow = apply_effect_order("ComposePathEffect", "Discrete(3,5)", "PathDash(12)")
sum_flow = apply_effect_order("SumPathEffect", "Discrete(3,5)", "PathDash(12)")
row_y_offsets = [10 + i * 60 for i in range(7)]
phases_5_frames = [0 + 2 * f for f in range(5)]
c4_actual = {
"compose_order": compose_flow,
"sum_layers": sum_flow,
"seven_row_y_offsets": row_y_offsets,
"phase_progression_5_frames": phases_5_frames,
}
c4_expected = {
"compose_order": ["stage1:PathDash(12)", "stage2:Discrete(3,5)(on PathDash(12))"],
"sum_layers": ["layer_a:Discrete(3,5)", "layer_b:PathDash(12)"],
"seven_row_y_offsets": [10, 70, 130, 190, 250, 310, 370],
"phase_progression_5_frames": [0, 2, 4, 6, 8],
}
cases = [
{
"name": "dash_patheffect_intervals_and_phase",
"summary": "核验 DashPathEffect([20,10,5,10], phase) 在相位 0 与 12 下的实线段分布及奇数数组校验",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "corner_and_discrete_patheffect_geometry",
"summary": "核验 CornerPathEffect(10) 在 90°/60° 夹角的切线回退与弧长,以及 DiscretePathEffect(3,5) 分段数",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "pathdash_advance_phase_and_styles",
"summary": "核验 PathDashPathEffect(advance=12) 相位推进及 ROTATE/MORPH/TRANSLATE 三种连接风格",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "compose_vs_sum_and_view_animation",
"summary": "核验 ComposePathEffect 顺序嵌套与 SumPathEffect 双层叠加语义,以及 7 行绘制偏移与 phase+=2 推进",
"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()
- 验证 DashPathEffect 相位偏移与偶数校验、CornerPathEffect 切线弧长、PathDashPathEffect 间距定位及 Compose/Sum 合成语义。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:3c01409228ad547cce440a57bb0e176a08985516912a8c2aa3a3e67ba70e5f22
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:83cc132e94da34b37d51dd239c4861ac3525b2558152065c4936edd74df4ad3d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`ComposePathEffect(outerpe, innerpe)` 与 `SumPathEffect(first, second)` 在效果叠加方式上有何本质区别?
展开参考解答
`ComposePathEffect` 是串行嵌套,先执行 `innerpe`,再在其输出路径上施加 `outerpe`(参数顺序不可互换);`SumPathEffect` 是并行叠加,分别独立计算 `first` 与 `second` 后将两者直接重叠绘制。